Derek Lawless

There is always sunshine / Far above the grey sky

Destructuring is one of the more useful language features added in ECMAScript 6 (ES6). Destructuring allows you to unpack values from arrays, or properties from objects, into distinct variables.

Consider the following object:

const user = {
	emailAddress: "billg@microsoft.com",
	nickName: "Bill G"
}

Pre-ES6 you would typically access the object property values directly or assign e.g.

console.log(`${ user.nickName } (${ user.emailAddress })`); // "Bill G (billg@microsoft.com)"

const emailAddress = user.emailAddress
const nickName = user.nickName;
console.log(`${ nickName } (${ emailAddress })`); // "Bill G (billg@microsoft.com)"

ES6 introduced destructuring, enabling you to unpack into new variables in one assignment expression:

const { emailAddress, nickName } = user;
console.log(`${ nickName } (${ emailAddress })`); // "Bill G (billg@microsoft.com)"

One awkward scenario is where you want to destructure an object but the resultant variable(s) already exist in scope. Here, the unpacked variables collide with the function arguments:

const getDetails = (emailAddress) => {
	return user; // Fetch existing details from a database, etc.
}

const updateDetails = (emailAddress, nickName) => {
	const { emailAddress, nickName } = getDetails(emailAddress);

	console.log(`${ nickName } (${ emailAddress })`);
}

updateDetails("steveb@microsoft.com", "Steve B"); // Uncaught SyntaxError: Identifier 'emailAddress' has already been declared

Fortunately, this scenario was anticipated and you can rename variables in a destructuring assignment:

const updateDetails = (emailAddress, nickName) => {
	const { emailAddress: currentEmailAddress, nickName: currentNickName } = getDetails(emailAddress); // Renaming

	console.log(`${ nickName || currentNickName } (${ emailAddress || currentEmailAddress })`);
}

updateDetails(); // "Bill G (billg@microsoft.com)"
updateDetails("steveb@microsoft.com", "Steve B"); // "Steve B (steveb@microsoft.com)"
© 2022 Derek Lawless. Built with Gatsby