Mutable values are values that can be changed without an entirely new value. In JavaScript objects and arrays are mutable by default.
As already said in a previous post about Immutable Primitive Values, there is a fundamental difference in JavaScript between primitive values (undefined, null, booleans, numbers, and strings) and objects (including arrays and functions).
First, objects are mutable:
let obj = { x: 1 }
o.x = 2 // obj = { x: 2 }
o.y = 3 // obj = { x: 2, y: 3 }
Second, objects are not compared by value, two objects are not equal even if they have the exact same values, this is true for arrays too:
let o = { x: 1 }, p = { x: 1 }
o === p // false
let a = [], b = []
a === b // false
JavaScript objects and arrays are compared by reference, two objects values are the same if and only if they refer to the same underlying object:
let a = []
let b = a // b refers to a
b[0] = 1
a[0] // 1 - changes are also visible in the array a
a === b // true
Thanks for Reading!
Top comments (0)