Widget Image
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna

Sorry, no posts matched your criteria.

Destructuring in ES6

Objects and arrays are the most commonly used data structures in JavaScript. They’re foundational to writing even the most basic pieces of code. They contain not only the values you’re using, but can also describe the relationship between the values. Arrays describe data in order, and object describe data by name. Nesting them creates even more information. You can have arrays of objects, objects containing arrays, and so on. As you can see, these structures are both quite simple and useful, and can also be combined and built up to make rather complex compound structures. This is a wonderful quality for storing and sending information concisely, but can become rather burdensome when you need to access and use the values contained within.

Starting with ES6, there is a new way to access objects and arrays called ‘destructuring’. It’s a fancy word that just means to pull information out of a structure. Destructuring with arrays is done by simply making an array with the relevant variable names, and using that on the left hand side of the assignment. The variables will be filled in, in order, from the array on the right hand side. To destructure objects, use curly braces to surround a list of the property names you wish to pull out as variables. The syntax is pretty straightforward, and some examples will help to illustrate it. Note that not all browsers support it, so it’s best to use Babel to ensure maximum compatibility of your code.

const rankings = [ 'gold', 'silver', 'bronze' ];

// old way
let firstPlace = rankings[0]; // 'gold'
let secondPlace = rankings[1]; // 'silver'

// with Array destructuring
let [ firstPlace, secondPlace ] = rankings;

const person = { firstName: 'Stephen', lastName: 'Hawking' };

// old way
let firstName = person.firstName; // 'Stephen'
let lastName = person.lastName; // 'Hawking'

// with Object destructuring
let { firstName, lastName } = person;

For both types of destructuring, it’s fine to have the assignment separate from the variable declaration, but with objects you have to surround the entire clause with parentheses to tell the parser that it’s an object destructring rather than a simple code block.

// with Object destructuring
let firstName, lastName;

{ firstName, lastName } = person; // SyntaxError: Unexpected token '='
({ firstName, lastName } = person); // correct

It’s possible to skip values in array destructuring by simply not supplying any name and moving on to the next comma. With objects, it is assumed you only want the values you explicitly ask for and everything else is ignored.

// destructure and skip an element
let [ firstPlace, , thirdPlace ] = rankings;

Sometimes you want to pull a few values out of an object or array and do something else with the remaining values. You can do that with the “rest” operator, which is an ellipsis (three dots) before the last variable name of the destructuring operator. The rest operator, if used, must always be last.

const rankings = [ 'gold', 'silver', 'bronze', 'fourth', 'fifth', 'sixth' ];

let [ gold, silver, bronze, ...nonMedalists ] = rankings;
// nonMedalists is now [ 'fourth', 'fifth', 'sixth' ]


const user = { username: 'turbo', password: '$ecret', status: 'online' };

let { password, ...publicInfo } = user;
// publicInfo is now { username: 'turbo', status: 'online' }

It can be preferable (or sometimes even necessary) to pull an item out of an object into a variable that is named differently than the name it has in the object. To do that, add a colon and the new variable name after the original property name in the left hand side object.

const id = 123;
const user = { id: 5 };

// pull user.id out into variable userID
let { id: userID } = user;
// userID is 5

Sometimes arrays and objects are flat, but most of the time they’re nested. Destructuring assignments can be nested too, as many levels as you like.

const user = {
	activity: {
		lastLogin: '2020-02-02 02:02:02',
		likes: [
			{ postId: 2 },
			{ postId: 10 },
		]
	}
}

const { activity: { lastLogin }, likes: [ latestLikedPostId ] } = user;
// lastLogin is '2020-02-02 02:02:02'
// latestLikedPostId = 2


const nestedArray = [
	[ 'a', 'b', 'c' ],
	{
		first: 'gold',
		second: 'silver',
		third: 'bronze',
	},
];

let [ [ a ], { second } ] = nestedArray;
// a is 'a', second is 'silver'

If the object property or array element that you reference doesn’t exist, you can provide a default value for it. After the variable name, add an equals sign and the value to set if the property or element is undefined. Note that object properties are searched all the way up the prototype chain before defaulting to the given value.

function login({ username, password, rememberUser = false }) {
	// don't save user session unless they request it
}


const pair = [ 'a', 'b' ];
let [ a, b, c = 'c' ] = pair;
// a is 'a', b is 'b', c is 'c'

Object properties can also be dynamic.

const identifier = 'displayName';

const user = {
	name: T'Challa,
	displayName: 'Black Panther',
};

let { [ identifier ]: name } = user;

And of course, you can mix and match all of the above techniques.

const displayName = 'firstName';

const hero = {
	firstName: 'Moana',
	userId: 1,
	hobbies: [
		'sailing',
		'voyaging',
	],
	friends: [
		{
			name: 'Pua',
			type: 'pig',
		},
		{
			name: 'Heihei',
			type: 'chicken',
		},
	],
};

let {
	[ displayName ]: name = 'Mystery Hero',
	friends: [ , , thirdBestFriend = { name: 'Maui', type: 'demigod' } ],
	hobbies: [ favoriteHobby, ...otherHobbies ]
} = hero;
// name is 'Moana'
// thirdBestFriend is { name: 'Maui', type: 'demigod' }
// favoriteHobby is 'sailing'
// otherHobbies is [ 'voyaging' ]

Destructuring is a powerful way to easily access the data contained within complex data structures of arrays and objects. It has innumerable potential uses, and can be employed anywhere ES6 is supported (directly or through transpilation). If you find yourself digging into objects or arrays to pull out values, consider destructuring to make your code cleaner.

I'd love to know what you think

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from JavaScript Artisan

Subscribe now to keep reading and get access to the full archive.

Continue reading