Last active
October 10, 2015 15:38
-
-
Save preslavrachev/3712783 to your computer and use it in GitHub Desktop.
JavaScript's assignment operation in more detail
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 == {} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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