JavaScript Value vs Reference

Muhammad Hassan
3 min readMar 12, 2021

JavaScript has 5 data types that are copied by value.

Primitives (copied by value)

  • null
  • undefined
  • Number
  • String
  • Boolean

JavaScript has 3 data types that are copied by having their reference copied.

Objects (copied by reference)

  • Object
  • Array
  • Function

These are all technically Objects.

Primitives

If a primitive type is assigned to a variable, we can think of that variable as containing the primitive value.

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

When we assign primitives to the variable, we copy the value.

Objects

Objects
var a = {};
var b = a;

a.a = 1;

console.log(a); // {a: 1}
console.log(b); // {a: 1}

Arrays
var a = [];
var b = a;

a.push(1);

console.log(a); // [1]
console.log(b); // [1]
console.log(a === b); // true

Variables that are assigned a non-primitive value are given a reference to that value. That reference points to the object’s location in memory. The variables don’t actually contain the value.

Objects are created at some location in our computer’s memory. When we write, arr = []we’ve created an array in memory. What the variable arr now contains is the address, the location, of that array.

When you assign a reference value from one variable to another, the value stored in the variable is also copied into the location of the new variable.

The difference is that the values stored in both variables now are the address of the actual object stored on the heap. As a result, both variables are referencing the same object.

Example:

Declare a variable x that holds an object whose name property is 'John'.

var x = {name: 'John'};

Declare another variable y and assign the x variable to y. Both x and y are now referencing the same object on the heap.

var y = x;

Now modify the value stored in the name property of the object using the y variable.

y.name = 'David';

Since both x and y are referencing the same object, the change is also reflected if you access the object using the x variable.

console.log(x.name); // 'David'

Comparison

In javascript we check if two variables are the same, using: == or ===.

let a = 2;
let b = 2;
console.log(a == b, a === b); // true, true
  • == checks if the values of the variables are the same
  • === checks if the variable's values and references are the same. In other words, it checks if both variables point to the same address in memory.
let a = { name: 'john' };
let b = { name: 'john' };
console.log(a == b, a === b); // true, false

let a = { name: 'john' };
let b = a;
console.log(a == b, a === b); // true, true

== will be true if the variables hold the same values and === will be true if the variables point to the same reference.

Resources:

--

--