Reference Vs Copy

1. String, Number, Boolean can be copied by assigning to another variable

let a = 10; let b = a; both becomes 10; but if we change b a is not changed unlike array. b = 9; Now, a is 10, but b is 9.

1. Array cannot be copied like others 3 data types

let arr = [1,2,3]; let arr2 = arr; arr2[1] = 4; Both has the same value now. There are several ways to copy an array :

  1. arr.splice() without any parameters
  2. [].concat(arr)
  3. [...arr]
  4. Array.from(arr)

1. Object also - assigning with another variable denotes reference

let a = { name: 'mine', age: 28 } let a = b; b['age'] = 29; Both has the same value. There are several ways to copy an object:

  1. Object.assign({}, anObj, {any : newValue})
  2. {...anObj}
  3. JSON.parse(JSON.stringify(anObj)) *Not recommended