I'm working through my course, and keep hitting the same speedbumb. My mental model for why the following behavior is lacking. I'm after as simple an explanation as possible to fill the gap :)
In the following snippet the reassignment doesn't occur for the qux variable when it's name is passed into the function.
let foo = {a: 'hello',b: 'world'};
let qux = 'hello';
function bar(argument1, argument2) {
argument1.a = 'hi';
argument2 = 'hi';
}
bar(foo, qux);
console.log(foo.a); // Logs 'hi'
console.log(qux); // Logs 'hello'
But in the below example, when the variable name is explicitly referenced in the function, and the value is passed as an argument, then the reassignment occurs.
let foo = {a: 'hello',b: 'world'};
let qux = 'hello';
function bar(argument1, argument2) {
argument1.a = 'hi';
qux = argument2;
}
bar(foo, 'hi');
console.log(foo.a); // Logs 'hi'
console.log(qux); // Logs 'hi'
I understand object values are mutable, and primitive values are not. However, I don't understand why JS is not reassigning the variable in both instances?
I've reviewed this question, the answers to which go into some depth, but I can't seem to see a specific answer for why the reassignment specifically isn't happening.