Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn ES6 Destructuring | Getting Started: ES6
Introduction to React

bookES6 Destructuring

The older method of accessing and assigning values from an array was indexing:

const myArray = ['car', 'jet', 'spaceship'];
const landVehicle = myArray[0];
const airVehicle = myArray[1];
const spaceVehicle = myArray[2];

However, ES6 has introduced a new method called destructuring, which enables us to access and assign values from an array easily:

const [ landVehicle, airVehicle, spaceVehicle ] = myArray;
console.log (landVehicle);

The above method is much neater and requires less code.

We can also skip the elements we don't want to capture, for example, we can skip airVehicle but add an extra comma:

const [ landVehicle, , spaceVehicle ] = myArray;

Note

The const keyword is for defining constant terms, you can also use the let keyword in the Destructuring statement.

question-icon

Complete the following code:

function stringVariants (str) {
    return [str.toLowerCase (), str.toUpperCase ()];
}
[,] = stringVariants ("Hello World!");
console.log (lower, upper);
hello world! HELLO WORLD!

Click or drag`n`drop items and fill in the blanks

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 1. ChapterΒ 6

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Awesome!

Completion rate improved to 2.7

bookES6 Destructuring

Swipe to show menu

The older method of accessing and assigning values from an array was indexing:

const myArray = ['car', 'jet', 'spaceship'];
const landVehicle = myArray[0];
const airVehicle = myArray[1];
const spaceVehicle = myArray[2];

However, ES6 has introduced a new method called destructuring, which enables us to access and assign values from an array easily:

const [ landVehicle, airVehicle, spaceVehicle ] = myArray;
console.log (landVehicle);

The above method is much neater and requires less code.

We can also skip the elements we don't want to capture, for example, we can skip airVehicle but add an extra comma:

const [ landVehicle, , spaceVehicle ] = myArray;

Note

The const keyword is for defining constant terms, you can also use the let keyword in the Destructuring statement.

question-icon

Complete the following code:

function stringVariants (str) {
    return [str.toLowerCase (), str.toUpperCase ()];
}
[,] = stringVariants ("Hello World!");
console.log (lower, upper);
hello world! HELLO WORLD!

Click or drag`n`drop items and fill in the blanks

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 1. ChapterΒ 6
some-alt