1

Consider the Two Snippets

const sayMyName = wizard => {
  wizard.name = 'Shazam';
}

let boy = { name: 'Billy' };

sayMyName(boy);

console.log(boy.name);

Since We know that objects in js are passed by reference hence a reference to boy object is assigned a property with value 'Shazam'. Since Object at the stored Reference is changed hence boy's name is changed to 'Shazam'.

const sayMyName = wizard => {
  wizard = { name: 'Shazam' };
}

let boy = { name: 'Billy' };

sayMyName(boy);

console.log(boy.name);

Considering above case Here When Boy is passed in sayMyName function why it is behaving as pass by value and boy.name still return 'billy' ?

4
  • Redefining a variable name, on its own, eg wizard = { name: 'Shazam' };, will almost never do anything unless the (reassigned) variable name is used lower in the scope for which it's defined. It's like var foo = 'foo'; var foo2 = foo; foo = 'bar'; - foo2 remains 'foo' Commented Mar 9, 2019 at 7:01
  • This is not related to scope i think the reason for this is it since it is a primitive data-type foo2 is given a new memory location and is not copied Commented Mar 9, 2019 at 7:57
  • It's moderately related - wizard = ... will change what referencing the wizard variable name refers to later in its scope, but that won't affect what variable names refer to which memory locations in the outer scope with boy. In my foo example, if you changed the 'foo' to { prop: 'val' }, you'd see the same thing. Regardless of the type of value a variable references, reassigning that variable name won't affect other references to the original value. Commented Mar 9, 2019 at 8:02
  • No variables are passed by reference in JS, and there are no exceptions to that. Commented Mar 9, 2019 at 12:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.