Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Destructuring / Spreading

You can destructure an object. You can spread an object. And, you can do both.

To destructure is to take the properties from an object or array and assign each property as it is iterated over, to a new variable. Names must match.

Spread is a new operator introduced in ECMA6. To spread an object is to take all the properties of that object and place it into an array. All the objects properties will become items in a new array or object.


// data
let person = { Name: "Ricky Bobby", Occupation: "Race Car Driver", Gender: "Male", Age: 45 };

// destructure
// person has Name & Occupation props.  Maybe others.
let {Name, Occupation} = person;
let destructureDemo = document.getElementById("destructure-demo");
destructureDemo.innerHTML = `Name: ${Name}, Occupation: ${Occupation}`;

// spread
let {...rickyBobby} = person;
let spreadDemo = document.getElementById("spread-demo");
spreadDemo.innerHTML = `Name: ${rickyBobby.Name}, Occupation: ${rickyBobby.Occupation}`;
// or
spreadDemo.innerHTML = `Name: ${rickyBobby["Name"]}, Occupation: ${rickyBobby["Occupation"]}`;

Destructure example:


Spread example: