Destructuring Arrays

Introduction

Destructuring arrays is similar to destructuring objects, however, there are some differences. In objects, we have key/value pairs where we reference a value using a key. In arrays, we have a list of elements and use an index to reference an element. There aren’t keys in an array.

Destructuring arrays

When we destructure from an array, we assign variable names to values from our array. The order in which we write our variable names directly relates to the order of the elements in the array.

javascript
	const [
	  /* values here */
	] = arrayName;
	
	// For example:
	const [value1, value2] = arrayName;

Array Destructuring Example 1

Let’s have a look at an array destructuring example. We have destructured the values at index 0 and index 1 to the values x and y:

javascript
	const coords = [12, 30, 5, 9, 100, 53];
	
	// 'x' is index 0 in the array
	// 'y' is index 1 in the array
	const [x, y] = coords;
	
	console.log(x, y);
	// Logs:
	// 12 30

Array Destructuring Example 2

Let’s have a look at another example. We have an array of names (names) and then destructure index 0 and index 1 to the variable names name0 and name1.

javascript
	const names = ['Ola', 'Kari', 'Joakim', 'Ole'];
	
	// 'name0' is index 0 in the array
	// 'name1' is index 1 in the array
	const [name0, name1] = names;
	
	console.log(name0, name1);
	// Logs:
	// Ola Kari

Ignoring values

You can choose to ignore values by simply having no variable.

javascript
	const values = [0, 1, 2, 3, 4];
	
	const [value0, , value2] = values;
	console.log(value0, value2);
	// Logs:
	// 0 2

Destructuring video

In this video, we take a look at destructuring arrays and objects.

Link to video

Lesson task

Destructuring is a normal part of being a JavaScript developer and you’ll be expected to destructure at the workplace. We are going to practice destructuring so you get used to it.

Goal

To be able to destructure arrays.

Brief

Fork or clone this repo and complete the exercises on your own computer: https://github.com/NoroffFEU/destructuring-exercises. Complete exercise-2.js.

NOTE: Don't try to merge your exercise with the main exercise repo, this is for your own practice.

Additional resources

MDN Docs: Destructuring assignment