Skip to content

Instantly share code, notes, and snippets.

@siwalikm
Last active Mar 14, 2020
Embed
What would you like to do?
JS reference and scope
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.

@siwalikm
Copy link
Author

siwalikm commented May 20, 2018

Please refer @rtablada's gist which explains how memories work in js here for better understanding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment