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' ?
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 likevar foo = 'foo'; var foo2 = foo; foo = 'bar';-foo2remains'foo'wizard = ...will change what referencing thewizardvariable name refers to later in its scope, but that won't affect what variable names refer to which memory locations in the outer scope withboy. In myfooexample, 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.