Javascript data types ( copy by value vs reference)

Understanding how Javascript data types are copied helps save time in debugging bugs. It is important to remember what data types are copied by value and what data types are copied by reference. By the end of this article, you will have a mental model of how computer memory is based on the data type.

Javascript has 8 data types out of which 5 are copied by value and 3 are copied by reference.

Primitives: Boolean, null, undefined, String, and Number

Objects: Array, Function, and Object

Primitives

When a primitive type is assigned to a variable, think of that variable like a box containing the primitive value.

var num = 10;
var word = 'a word';
var truth = false;
var z = null;

Assigning variables that contain primitives will copy by value. What it means when we say copy by value is that changing one variable does not change the other.

var numCopy = num;
num = 20;
console.log(num, numCopy) // 20, 10

Objects

When a object is assigned to a variable, the variable is given a reference to that value. The variable doesn’t actually contain the value.

var object = {a: 1, b: 2};
var copy = object;
object.a = 5;
console.log(copy.a) // 5
// Observe the next example carefully
var object2 = [1, 2, {"foo": 3}];
var primitiveCopy = object2[1];
var objectCopy = object2[2];
console.log(primitiveCopy, objectCopy); // 2, {"foo": 3}
object2[2].foo = "some string";
object2[1] = 0;
console.log(object2, primitiveCopy, objectCopy) 
// [1,0,{"foo":"some string"}], 2, {"foo": "some string"}
// Observe that objectCopy also changed because it is copied by
// reference
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.