Destructuring in Javascript

Viral Patel
PathFactory
Published in
2 min readApr 12, 2019

Destructuring assignment, introduced in ES6, lets you unpack values from arrays and properties of objects and save them into distinct variables. Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to an array or object literals.

Examples

Array destructuring

const [a, b] = ["This", "That"]
console.log(a) // "This"
console.log(b) // "That"
const [a, b, ...rest] = ["This", "That", "Else", "is", "rest"]
console.log(a) // "This"
console.log(b) // "That"
console.log(rest) // ["Else", "is", "rest"]

Fallback to default values

Array values can be destructured into variables positionally. Any missing values will use the default values specified.

const [email = "john@abc.com", name = "John"] = ["john@gmail.com"];console.log(email); // "john@gmail.com"
console.log(name); // "John"

Swapping Variables

We can use the destructuring assignment to swap the values of variables. With this, you no longer need to use intermediate variables to swap the values of the assigned variables.

var x = 33;
var y = 20;
[x, y] = [y, x]
console.log(x); // 20
console.log(y); // 33

Object destructuring

const data = {
user: { id: 1, name: "John Doe" }
}
const { user } = data;
console.log(user); // { id: 1, name: "John Doe" }

Nested Object destructuring

const data = {
user: { id: 1, name: "John Doe" }
}
const { user: { id, name } } = data;
console.log(id); // 1
console.log(name); // "John Doe"
// For more complex cases, the left side must have the same
// structure as the right side.

Fallback to default values

With destructuring, we can set defaults or fallback values so that if an item is not in the object (or Array, Map, or Set) it will fall back to what you have set as the default.

const styles = { width: 100 };const { width = 50, height = 50 } = styles;
console.log(width); // 100
console.log(height); // 50

Note: ES6 destructuring default values only kick in if the value is undefined. If the returned value is false, null, or 0, it will not use the defaults.

Summary

Destructuring assignment allows for instantly mapping an object or array onto many variables resulting in saving us a couple of lines of code per function.

This syntax is more declarative and makes the intention clear.

The alternative to array destructuring would be to access and default things based on array index etc, which is less clear.

Destructuring in ES6 has already changed the way javascript applications are written.

You can learn more about destructuring at this link. https://babeljs.io/docs/en/learn/

--

--