I'm doing some programming in node these days and I'm kinda surprised by the handling of scope in functions. I was led to believe that now with ES6 scope is a lot stricter. The following works as expected:
function f(v){
v += 1;
return v;
}
let before = 1;
let after = f(before);
console.log(after); // This logs 2 (as expected)
console.log(before); // This logs 1 (as expected)
But when I do the same using a object/dictionary, the scope of the variable seems to go outside the function:
function f(v){
v.a += 1;
return v;
}
let before = {a: 1};
let after = f(before);
console.log(after.a); // This logs 2 (as expected)
console.log(before.a); // This also logs 2 (I was expecting this to still be 1)
Why on earth is this the case? Why is the scope of v
limited to the function when it's an int
, but not when it's an object?