js object destructuring with defaults

JS Object Destructuring with Defaults

JS Object Destructuring is a powerful technique that allows developers to extract properties from objects and bind them to variables. It is a shorthand for extracting multiple properties from an object and saving them into separate variables, instead of manually accessing each property using dot notation.

Syntax


const {property1, property2, ...} = object;

For example, let's assume we have an object called person with properties name and age:


const person = {
  name: 'John',
  age: 30,
};

We can extract the properties using object destructuring:


const {name, age} = person;
console.log(name); // Output: John
console.log(age); // Output: 30

Default Values

JS Object Destructuring also provides the ability to set default values for properties that may not exist in the object. This is done by adding a default value after the property name, separated by an equals sign (=).


const {property = defaultValue} = object;

Let's take the previous example and add a default value for the property 'gender':


const person = {
  name: 'John',
  age: 30,
};

const {name, age, gender = 'unknown'} = person;
console.log(gender); // Output: unknown

If the property 'gender' does not exist in the object, the default value 'unknown' will be assigned to the variable.

Multiple Ways to Destructure Objects

There are multiple ways to destructure objects in JavaScript. One way is to use the dot notation to access the properties:


const person = {
  name: 'John',
  age: 30,
};

const name = person.name;
const age = person.age;
console.log(name); // Output: John
console.log(age); // Output: 30

Another way is to use array destructuring:


const person = {
  name: 'John',
  age: 30,
};

const arr = Object.entries(person);
const [property1, value1] = arr[0];
const [property2, value2] = arr[1];
console.log(property1); // Output: name
console.log(value1); // Output: John
console.log(property2); // Output: age
console.log(value2); // Output: 30

However, using object destructuring is the most concise and readable way to extract properties from objects.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe