PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] Why is it not possible to set null to an Object passed by reference in JavaScript?

 July 06, 2022     javascript, pass-by-reference     No comments   

Issue

I don't know why in the following example it is not possible to define null to the object, however it is possible to add properties to it

function callByReference(myFunc) {
  myFunc.b = 2;
  myFunc = null; // this not set null to Object arg

  // myFunc.b = 2; //If I set it after, throws error
}


let customObj = {
  a: 1
};

console.log("Before call by reference method");
console.log(customObj);

callByReference(customObj);

console.log("After call by reference method");
console.log(customObj);

Even if I set it null first and then adding a property throws an error;

I don't understand this behavior well. Is there any reason? maybe I'm not understanding how javascript works when passing by reference a argument


Solution

The way Javascript works, every variable name is essentially a pointer (or reference) to some value. When you create a new variable by referencing an old object, or when you call a function, you're basically copying the pointer. Eg:

const fn = (param) => {
  // ...
};
const obj = {};
const obj2 = obj;
fn(obj);

Above, obj2 and param both point to the empty object that was initially created in obj, you might think of it as:

obj: MemAddress1234
obj2: MemAddress1234
param: MemAddress1234

Whenever you use the = assignment operator, you reassign the binding for that variable name, but doing so doesn't affect any other variables that may have pointed at the same thing:

param = null;

results in something like

obj: MemAddress1234
obj2: MemAddress1234
param: MemAddress0

At least, that's one way to look at it. The link between obj and the empty object, and the link between obj2 and the empty object, remain unaffected, because it's only the param variable name was reassigned.

Reassigning a variable by itself will almost never have any side-effects on anything else. The two exceptions are with arguments in sloppy mode:

function foo(a, b) {
  console.log(arguments);
  a = 5;
  console.log(arguments);
}

foo(1, 2);

and with mutable variables exported by ES6 modules.



Answered By - CertainPerformance
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing