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

https://www.w3schools.com/jsref/jsref_obj_array.asp

You can dynamically declare variables from the indexes/positions of the array and set their values from an array. This is known as array destructuring. You can even skip positions in the array.


let numbers = [1,2,3,4,5];
let [number1, number2, number3,,number5] = numbers;    // note how I skipped the 4th item with double commas...
let demoLabel = document.getElementById("demo");
demoLabel.innerHTML = `${number1}, ${number2}, ${number3}, ${number5}`;

results:

 

You can even destructure them into two arrays by using the ... Spread operator to build a second array.


let numbers2 = [100, 200, 300, 400, 500];
let [first, ...restOfItems] = numbers2;
let demoLabel2 = document.getElementById("demo2");
demoLabel2.innerHTML = `${first.toString()}<br />${restOfItems.toString()}`;

results:

 

Here is a more practical example. Now we're destructuring an object and not an array so technically this should be on another page....but you get the point.


let rawData = {Junk1: "foo", Junk2: "bar", Name: "Ricky Bobby", Occupation: "Race Car Driver"};
let {junk1, junk2, ...scrubbedPerson} = rawData; // we now have discard junk props and now have a clean object
junk1 = null;
junk2 = null;
let demoLabel3 = document.getElementById("demo3");
demoLabel3.innerHTML = `Name: ${scrubbedPerson.Name}, Occupation: ${scrubbedPerson.Occupation}`;

results: