Unpack Arrays and Objects

In the last video, you read === as “same arrow?” and saw why .includes() can’t find a day record that only looks like one in the plan. Comparing asks whether two names reach one object. Most of the time, though, the planner script needs the values inside a record, such as who cooks on Monday and what’s for dinner.

In this lesson, you’ll pull those values out with destructuring, a short syntax that unpacks an object or an array into separate variables in one line. You’ll be able to read a pattern and say which variables it creates and what they hold, and you’ll finish by swapping two of next week’s dinners in a single line. Start with Monday’s record.

Unpack a Record by Name

Reading several properties of one record repeats the record’s name on every line. To print Monday’s cook and meals, you’d write const day = monday.day;, then const cook = monday.cook;, and so on, typing monday. and the property name again each time.

Object destructuring says the same thing once. Create unpack.js and put a pattern in curly braces on the left of the equals sign:

Language: JavaScript Filename: unpack.js
const monday = {
  day: "Monday",
  cook: "Ngozi",
  meals: ["leftover rice", "jollof rice"],
};

const { day, cook, meals } = monday;

console.log(day, "is cooked by", cook);
console.log("Meals:", meals);

Run it, and the three new variables hold Monday’s values:

Language: Shell
$ node unpack.js
Monday is cooked by Ngozi
Meals: [ 'leftover rice', 'jollof rice' ]

The line const { day, cook, meals } = monday; declares three constants. Each name in the braces is a property to read, and the variable it creates has the same name. JavaScript matches them by name, so the order inside the braces doesn’t matter: { meals, day } works as well. A name the record doesn’t have, such as { dessert }, gives you a variable holding undefined. Reading monday.dessert gives the same value, and neither raises an error.

Rename and Fill in Missing Values

Matching by name has a cost when you unpack two records. Monday and Sunday both have a cook property, and one script can’t declare const cook twice. A pattern can give the value a new name with a colon:

Language: JavaScript Filename: cooks.js
const monday = { day: "Monday", cook: "Ngozi" };
const sunday = { day: "Sunday", cook: "Grandma Ifeoma" };

const { cook: mondayCook } = monday;
const { cook: sundayCook } = sunday;

console.log("Monday:", mondayCook);
console.log("Sunday:", sundayCook);

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.