Destructuring is a short hand way of assigning const
s in Javascript to be the elements of collections (arrays and objects)
Example:
const [x, y] = [1, 2]
console.log(x)
// prints 1
console.log(y)
// prints 2
similarly:
const myArray = [1, 2]
const [x, y] = array
console.log(x)
// prints 1
console.log(y)
// prints 2
similarly:
const arrayFunction = () => [1, 2]
const [x, y] = arrayFunction()
console.log(x)
// prints 1
console.log(y)
// prints 2
This also works with the spread operator:
const [x, y, ...theRest] = [1, 2, 3, 4, 5, 6]
console.log(x)
// prints 1
console.log(y)
// prints 2
console.log(theRest)
// prints [3, 4, 5, 6]
You can destructure in function parameters as well:
const myFunction = ([x, y]) => {
console.log(x)
console.log(y)
}
myFunction([1, 2])
// prints 1
// prints 2
Example:
const {a, b} = {a: 1, b: 2}
console.log(a)
// prints 1
console.log(b)
// prints 2
The keys must match the keys in the object on the right hand side:
const {z} = {a: 1, b: 2}
console.log(z)
// prints undefined
const {a, c, e} = {a: 1, b: 2, c: 3, d: 4, e: 5}
console.log(a)
// prints 1
console.log(c)
// prints 3
console.log(e)
// prints 5