Dup Ver Goto 📝

object-destructuring

PT2/lang/js/lang does not exist
To
50 lines, 292 words, 1477 chars Page 'object-destructuring' does not exist.

The one I always forget is

const { a: a1, b: b1 } = obj;

where the key is the member name in obj and the value is what we want to call it.

From mozilla.org

const [a, b] = array;
const [a, , b] = array;
const [a = aDefault, b] = array;
const [a, b, ...rest] = array;
const [a, , b, ...rest] = array;
const [a, b, ...{ pop, push }] = array;
const [a, b, ...[c, d]] = array;

const { a, b } = obj;
const { a: a1, b: b1 } = obj;
const { a: a1 = aDefault, b = bDefault } = obj;
const { a, b, ...rest } = obj;
const { a: a1, b: b1, ...rest } = obj;
const { [key]: a } = obj;

let a, b, a1, b1, c, d, rest, pop, push;
[a, b] = array;
[a, , b] = array;
[a = aDefault, b] = array;
[a, b, ...rest] = array;
[a, , b, ...rest] = array;
[a, b, ...{ pop, push }] = array;
[a, b, ...[c, d]] = array;

({ a, b } = obj); // brackets are required
({ a: a1, b: b1 } = obj);
({ a: a1 = aDefault, b = bDefault } = obj);
({ a, b, ...rest } = obj);
({ a: a1, b: b1, ...rest } = obj);

Destructuring without var, let or const

From this stackoverflow

// use () grouping
let a,b
( [a,b] = [1,2] )
let o = { a:3, b:4 }
( {a,b} = o )

This is useful when we want to set scope with let, but then want to destructure differently in different branches of if-else.