๐Ÿ”ฐdestructuring array

JS โŸฉ operator โŸฉ assignment โŸฉ destructuring โŸฉ array

๐Ÿ’พ ็จ‹ๅผ๏ผšreplit

// array destructuring
let [a, b] = ["John", "Smith"]
let [a, b] = "John Smith".split(' ')

let [a, , c] = ["hi","what","hello"];  // โญ ignore elements
let [a, b, ...rest] = "abcdef"         // โญ "rest" (array)
let [s, t = 0] = [1];                  // โญ default values

let [
    name = prompt('name?'),            // โญ return value as default
    surname = prompt('surname?')
] = ["Julius"];

// tricks

// โญ assign to object's properties
let user = {};
[user.name, user.surname] = "John Smith".split(' ');
// user = { name: 'John', surname: 'Smith' }

// โญ "swap" trick
let [p, q] = [1, 2];
[p, q] = [q, p];                     // p=2, q=1

Last updated

Was this helpful?