DEV Community

loading...

Using Destructuring Assignment to Extract Values from Objects

Randy Rivera
Once I truly put my mind on something, I won't ever stop.
・1 min read

Destructuring assignment is special syntax introduced in ES6, for neatly assigning values taken directly from an object.

  • Consider the following ES5 code:
const HIGH_TEMPERATURES = {
  yesterday: 75,
  today: 77,
  tomorrow: 80
};

const yesterday = HIGH_TEMPERATURES.yesterday;
const today = HIGH_TEMPERATURES.today;
Enter fullscreen mode Exit fullscreen mode
  • yesterday would have a value of 75, and would have the value 77.

  • Now let's Replace the two assignments with an equivalent destructuring assignment. It should still assign the variables today and tomorrow the values of today and tomorrow from the HIGH_TEMPERATURES object.

const { today, tomorrow } = HIGH_TEMPERATURES;
Enter fullscreen mode Exit fullscreen mode
console.log(today); will display 77
console.log(tomorrow); will display 80
Enter fullscreen mode Exit fullscreen mode

Discussion (0)