var foo = {'bar': 1};
function overwriteFoo(obj) {
obj = {'bar': 2};
}
function overwriteFooBar(obj) {
obj.bar = 2;
}
overwriteFoo(foo)
// console.log(foo) = {'bar': 1};
overwriteFooBar(foo)
// console.log(foo) = {'bar': 2};
Explanation
var foo = {'bar': 1};
Identifier | Memory Location | Value | typeof |
---|---|---|---|
foo | OBJ001 | {'bar': 1} |
Object |
function overwriteFoo(obj) {
obj = {'bar': 2};
}
Identifier | Memory Location | Value | typeof |
---|---|---|---|
foo | OBJ001 | {'bar': 1} |
Object |
obj | OBJ002 | REF:OBJ001 | Object |
Setting a value to obj
actually sets it to OBJ002
. You are changing what obj
points to inside of the function (it doesn’t change anything outside of that function).
function overwriteFooBar(obj) {
obj.bar = 2;
}
Identifier | Memory Location | Value | typeof |
---|---|---|---|
foo | OBJ001 | {'bar': 1} |
Object |
obj.bar | REF:OBJ001 | 2 |
Number |
By setting obj.bar
you follow the pointer obj
to the object at memory OBJ001
and then change the value of bar
inside of the object.
This comment has been minimized.
Please refer @rtablada's gist which explains how memories work in js here for better understanding.