Back to roots: JavaScript Value vs Reference

Miro Koczka
Sep 13, 2017 · 3 min read
console.log([10] === [10]);

var oldArray = [];
var object = {};
object.newArray = oldArray;
oldArray.push(10);
console.log(object.newArray === oldArray);


Primitives

var a = 5;var b = a;a = 10;console.log(a); // 10
console.log(b); // 5
// this is also true for string, boolean, null, undefined

Objects

var a = {};
var b = a;
a.a = 1;console.log(a); // {a: 1}
console.log(b); // {a: 1}
var a = [];
var b = a;
a.push(1);console.log(a); // [1]
console.log(b); // [1]
console.log(a === b); // true
var a = [];     # Address #001 -> []
# Variable a -> #001
var b = a; # Variable b -> #001a.push(1); # Address #001 -> [1]Variable | Address | Value
a | #011 | [1]
b | #011 | [1]

Now, about the [10] === [10] example

JSON.stringify(a) === JSON.stringify(b)

Conclusion

DailyJS

JavaScript news and opinion.

Miro Koczka

Written by

Software engineering, Product development, Growth Hacking. I enjoy building web & mobile applications people love to use. More about me on www.mirokoczka.com

DailyJS

DailyJS

JavaScript news and opinion.