let x = [];
What is the content of x
? If you said an empty array you would be wrong, strictly speaking. The right answer is that x
contains a reference (e.g. <#525>
) which points to a memory location which contains the value []
.
let x = 5;
What is the content of x
here? You read the previous paragraph and say: It contains a reference which points to a memory location which contains the value 5
? That would be wrong. This time it does simply contain the value 5
, no references included.
Why? What is so different between []
and 5
, is that []
is an object
data type and 5
is a primitive data type.
JavaScript has five primitive data types: Boolean
, null
, undefined
, String
, and Number
. The rest are objects, including Array
, Function
and Object
.
Primitive types are copied by value.
let x = 1; // x contains 1 let y = x; // y contains copy (not reference) of x which is 1 y = 2; // overwriting with 2 does not affect x in any way console.log(x === 1); // true console.log(y === 2); // true
Objects are copied by having their reference copied:
const obj = { innerObj: { x: 9 } }; const z = obj.innerObj; z.x = 25; console.log(obj.innerObj.x); // 25
With const z = obj.innerObj;
z contains a reference which points to the memory location which stores the value of innerObj
.
const obj = { arr: [{ x: 17 }] }; let z = obj.arr; z = [{ x: 25 }]; console.log(obj.arr[0].x); // 17
With z = [{ x: 25 }];
we overwrote the reference that z contained before. It is now unreachable and gets garbage collected by JavaScript.
const obj = { arr: [] }; obj.arr.push(17); console.log(obj.arr === [17]); // false
obj.arr
does contain [17]
but not the [17]
that we are comparing with in the last line.