Last Updated: February 25, 2016
· jjperezaguinaga
Me 180x180

Storing by value vs Storing by reference in Javascript

Primitive values are stored by value, while Objects are stored by reference. The main primitive values are Number, Boolean, String, null and undefined (people will argue the last two are actually values, but they follow the same rules in memory storage when compared to primitive values). The "complex" values (as of ECMAScript 262 Ed. 3) are Object, Array, Function, Date, Error and RegExp. Here's an example:

var a = 10
var b = a
a // returns 10
b // returns 10
a = 20
a // returns 20
b // returns 10

in contrast to

var a = {}
var b = a
a // returns {}
b // returns {}
a.foo = "bar"
a // returns {foo: "bar"}
b // returns {foo: "bar"}

As a good exercise, comparing complex objects is made by reference, not value. This means that you are really comparing the memory address they are being stored at

var a = { foo: "bar" }
var b = { foo: "bar" }
a === b // returns false
b = a
a === b // returns true
Say Thanks