Skip to content

Instantly share code, notes, and snippets.

@preslavrachev
Last active October 10, 2015 15:38
Show Gist options
  • Save preslavrachev/3712783 to your computer and use it in GitHub Desktop.
Save preslavrachev/3712783 to your computer and use it in GitHub Desktop.
JavaScript's assignment operation in more detail
var x = 2 // x gets a reference to the value of the scalar 2;
var y = x // also gets a reference to the value of the scalar 2; Please, note that y does not refer to x, but //to the value to which x refers. That will make more sense in the later examples.
x++;
y = ??? x = ??? // x == 3, while y==2, because x was given a new reference to the value of the scalar 3. Since //y points a reference to the value of the scalar 2, and not to x, it keeps the value
//Same for arrays and objects
var x = {}
var y = x // copies the value of x as the initial value of y => keeps a reference to the value of x ({}),
//not x itself
therefore:
y = {abc:"test"} //changes the reference to completely different value, but x == {}
//All of this should be clear. Now the tricky case:
var x = {}
var y = x
x.abc = "test"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment