Objects and Properties
Object Destructuring
Pull named fields out of an object literal.
object-destructuring
Destructuring binds selected properties to local variable names. The later code uses the new variables directly.
Object Destructuring
destructuring.js
Replay: real traced execution (multi-file project)
const boost = 2;
const { name, points } = { name: "Ada", points: 10 + boost };
const level = points >= 12 ? "high" : "base";
console.log("name=" + name);
console.log("points=" + points);
console.log("level=" + level);
const boost = 0;
const { name, points } = { name: "Ada", points: 10 + boost };
const level = points >= 12 ? "high" : "base";
console.log("name=" + name);
console.log("points=" + points);
console.log("level=" + level);
const boost = 5;
const { name, points } = { name: "Ada", points: 10 + boost };
const level = points >= 12 ? "high" : "base";
console.log("name=" + name);
console.log("points=" + points);
console.log("level=" + level);
boost ← 2, name ← Ada, points ← 12, level ← high
1const boost→ 2 = 2; //@boost=0, 52const { name→ Ada, points→ 12 } = { name: "Ada", points: 10 + boost2 };3const level→ high = points→ 12 >= 12 ? "high" : "base";45console.log("name=" + nameAda);6console.log("points=" + points12);7console.log("level=" + levelhigh);outputname=Ada points=12 level=high
boost ← 0, name ← Ada, points ← 10, level ← base
1const boost→ 0 = 0;2const { name→ Ada, points→ 10 } = { name: "Ada", points: 10 + boost0 };3const level→ base = points→ 10 >= 12 ? "high" : "base";45console.log("name=" + nameAda);6console.log("points=" + points10);7console.log("level=" + levelbase);outputname=Ada points=10 level=base
boost ← 5, name ← Ada, points ← 15, level ← high
1const boost→ 5 = 5;2const { name→ Ada, points→ 15 } = { name: "Ada", points: 10 + boost5 };3const level→ high = points→ 15 >= 12 ? "high" : "base";45console.log("name=" + nameAda);6console.log("points=" + points15);7console.log("level=" + levelhigh);outputname=Ada points=15 level=high
Pull Out Fields
booststarts as2.- The object has
name: "Ada"andpoints: 10 + boost. - Destructuring creates local
nameandpointsvariables. points >= 12is true.- The level becomes
high. | Field | Local variable | Value | | --- | --- | --- | |name|name|Ada| |points|points|12|
Exercise: destructuring.js
Destructure name and points from an object, then label the level from the points