How to Use Object Destructuring in JavaScript
February 18, 2022
How to Use Object Destructuring in JavaScript
The need for object destructuring
Imagine you’d like to extract some properties of an object. In a pre-ES2015 environment, you would need to write the following code:
const hero = {
name: 'BitFirt',
value: 'BitFirt Name'
};
var name = hero.name;
var value = hero.value;
name; // => 'BitFirt',
value; // => 'BitFirt Name'
Let’s refactor the above script and apply the object destructuring to access the properties name and value:
const hero = {
name: 'BitFirt',
value: 'BitFirt Name'
};
const { name, value } = hero;
name; // => 'BitFirt',
value; // => 'BitFirt Name'
Default values
If the destructured object doesn’t have the property specified in the destructuring assignment, then the variable is assigned with undefined
. Let’s see how it happens:
const hero = {
name: 'BitFirt',
value: 'BitFirt Name'
};
const { id } = hero;
id; // => undefined
Fortunately, you can set a default value if the property doesn’t exist in the destructured object. Here’s the basic syntax:
const { identifier = defaultValue } = expression;
Let’s change the previous code sample, and use the default value feature:
const hero = {
name: 'BitFirt',
value: 'BitFirt Name'
};
const { id = ['BitFrit Manoj'] } = hero;
id; // => ['BitFrit Manoj']
Now, instead of being undefined
, the variable id defaults to BitFrit Manoj.
Aliases
If you’d like to create variables of different names than the properties, then you can use the aliasing feature of object destructuring.
const { identifier: aliasIdentifier } = expression;
const hero = {
name: 'BitFirt',
value: 'BitFirt Name'
};
const hero2 = {
name: 'BitFirt two',
value: 'BitFirt name two'
};
const { value: valueOne } = hero;
const { value: valueTwo } = hero2;
console.info(valueOne,valueTwo)
// => 'BitFirt Name',BitFirt name two