Skip to content

Instantly share code, notes, and snippets.

@siwalikm
Last active June 24, 2023 05:54
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siwalikm/dbf0e71f6e7e3406369b2cff1a6eb416 to your computer and use it in GitHub Desktop.
Save siwalikm/dbf0e71f6e7e3406369b2cff1a6eb416 to your computer and use it in GitHub Desktop.
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

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