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' ?

Webor
  • 11
  • 3
  • 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'` – CertainPerformance Mar 09 '19 at 07: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 – Webor Mar 09 '19 at 07: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. – CertainPerformance Mar 09 '19 at 08:02
  • No variables are passed by reference in JS, and there are no exceptions to that. – Bergi Mar 09 '19 at 12:26

0 Answers0