Skip to content

Array destructuring in JavaScript

Array destructuring assigns the properties of an array to variables with the same names by default. Here are a few examples.

//Basic
const [a, b, c] = [1, 2, 3] //a=1, b=2, c=3

//Declare and assign a value
let a, b
[a, b] = [1, 2]

//Skip some value
const [a, , b] = [1, 2, 3] // a=1, b=3

//Rest parameter
const [a, ...b] = [1, 2, 3] // a=1, b=[2,3]

//Fail-safe
const [, , , a, b] = [1, 2, 3] // a=undefined, b=undefined

//Swap value
const a = 1, b = 2;
[b, a] = [a, b] //a=2, b=1

//Multi-dimensional array
const [a, [b, [c, d]]] = [1, [2, [[[3, 4], 5], 6]]]  // a=1, b=2, c=[ [ 3, 4 ], 5 ], d=6

//String
const str = "hello";
const [a, b, c, d, e] = str // a='h',b='e',c='l',d='l',e='o'

Source

See also  Python code snippet - How to make wikipedia ?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.