๐Ÿ”ฐobject destructuring

JS โŸฉ operator โŸฉ assignment โŸฉ destructuring โŸฉ object

let opts = { title: "Menu", width: 100, height: 200};

// โญ object destructuring
let {title, width, noSuchThing} = opts;     // noSuchThing = undefinedโ—

// โญ rename variables
let {title: t, width: w} = opts;            // t = "Menu", w = 100

// โญ default values (could be function valuesโ—)
let {width: w2 = 100, title: t2} = opts;    // t2 = "Menu", w2 = 100

// โญ the "rest" object
let {title: t3, ...rest} = opts;            // rest = {width: 100, height: 200}

๐Ÿ‘‰ replit

// โญ๏ธ ๅฏๅ…ˆๅฎฃๅ‘Š่ฎŠๆ•ธ๏ผŒๅ† destructuring๏ผŒไฝ†่ฆใ€Œๅฐๅฟƒใ€โ—
let t, w, h;

// ------------------ ๐Ÿงจโ€ƒthere's a catchโ— --------------------
// โ›” SyntaxError: Unexpected token '='
//  {t, w, h} = opts;
//  ^^^^^^^^^ <------------ JS sees this as a "code block"โ—
// ------------------------------------------------------------

// โœ… wrap it in "parentheses", now it's OK.
    ({title: t, width: w, height: h} = opts);
//  ^                              ^

Last updated