tl;dr You can use destructuring to unpack values from arrays and properties from objects into variables.
const obj = {
a: 'a',
b: 'b',
c: 'c'
}
const arr = [1, 2, 3]
// to access a, b, and c
const a = obj.a
const b = obj.b
const c = obj.c
const first = arr[0]
// using destructuring is faster!
const { a, b, c } = obj
const [first] = arr
Resting (not 😴 but ...
) is to group multiple elements during destructuring into one element
const arr = [1, 2, 3]
const obj = {
a: 'a',
b: 'b',
c: 'c',
}
// using rest when destructuring
const [first, ...rest] = arr
console.log(first, rest) // first = 1, rest = [2, 3]
const { a, ...restObj } = obj
console.log(a, restObj) // a = 'a', restObj = { b: 'b', c: 'c' }
Beware! Though the same syntax as rest with ...
, it is the opposite!
tl;dr You can expand an iterable
Useful when creating a duplicate/clone of an object or array that’s not the same instance
const a = [1, 2, 3]
const newA = a
a[0] = 4
console.log(newA[0]) // prints 4, obviously not what we want! ❌
// the correct way to clone
const b = [1, 2, 3]
const clonedB = [...b] // here we use the spread syntax (on the left side of the expression)
b[0] = 4
console.log(clonedB[0]) // prints [1, 2, 3], which is as intended! ✅
You can add/update an object’s property easily
const obj = {
a: 'a',
b: 'b',
c: 'c'
}
// incorrect way
const sameObj = {
c: 'd',
...obj
}
// since the 'c' property is before the spread, the updated property will be overridden
// correct way
const updatedObj = {
e: 'e',
...obj, // spread first
c: 'd' // the updated property will override obj.c
d: 'd' // we can even add new properties! This time, it doesn't matter where we put it since it won't be overriden
}