Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

Array Destructuring

We can assign values from an array to our own variables.

Example

// Create an Array
const fruits = [“Bananas”“Oranges”“Apples”“Mangos”];

// Destructuring
let [fruit1, fruit2] = fruits;

Skipping Array Values

We can omit array values by using two or more commas.

Example

// Create an Array
const fruits = [“Bananas”“Oranges”“Apples”“Mangos”];

// Destructuring
let [fruit1,,,fruit2] = fruits;

Array Position Values

We can extract values from specific index positions in an array.

Example

// Create an Array
const fruits = [“Bananas”“Oranges”“Apples”“Mangos”];
// Destructuring
let {[0]:fruit1 ,[1]:fruit2} = fruits;

The Rest Property

You can conclude a destructuring statement with a rest property, which will collect all remaining values into a new array.

Example

// Create an Array
const numbers = [10203040506070];

// Destructuring
const [a,b, ...rest] = numbers

Destructuring Maps

Example

// Create a Map
const fruits = new Map([
  [“apples”500],
  [“bananas”300],
  [“oranges”200]
]);

// Destructing
let text = “”;
for (const [key, value] of fruits) {
  text += key + ” is “ + value;
}

Swapping JavaScript Variables

You can swap the values of two variables using destructuring assignment.

Example

let firstName = “John”;
let lastName = “Doe”;

// Destructing
[firstName, lastName] = [lastName, firstName];