Skip to main content

Command Palette

Search for a command to run...

JavaScript Destructuring Assignment - 1

Updated
•2 min read•View as Markdown
JavaScript Destructuring Assignment - 1
B

Web technology related ➡️ blogger || video creator || author || online instructor || YouTuber || web developer || freelancer


In the previous article, we've seen how to extract property values from an object and store them as variables.

const person = {
  name: 'Bello',
  age: 27,
  size: {
    height: 6.7,
    weight: 220
  }
};

const heightSize = person.size.height;
// const weightSize = person.size.weight;

console.log(`${person.name} is ${heightSize}" tall.`);

There's a technique called destructured assignment that easily extracts properties from an object.

Syntax:

{ key } = obj;

See the example below:

const person = {
  name: 'Bello',
  age: 27,
  size: {
    height: 6.7,
    weight: 220
  }
};

const { name } = person;
const { age } = person;

console.log(`${name} is ${age} years old.`);

Multiple property names in the same object (above example) can be accessed as shown below:

const { name, age } = person;
console.log(`${name} is ${age} years old.`);

To extract a nested object property, the syntax is shown below:

Syntax:

{ keyN } = globalObj.objkey1.objkey2...objkeyN;

See the example below:

const person = {
  name: 'Bello',
  age: 27,
  size: {
    height: 6.7,
    weight: 220
  }
};

const { name } = person;
// const { height } = person.size;
const { weight } = person.size;

console.log(`${name} weighs ${weight}lbs.`);

See more examples below:

let a, b, c = 4, d = 8; // a = 4, b = 4, c = 4, d = 8
[ a, b = 6 ] = [ 2 ]; // a = 2, b = 6

[ c, d ] = [ d, c ] // [ 8, 4 ] => c = 8, d = 4

let x, y;
( { x, y } = { x: 'Hello ', y: 'Bello' } );

console.log(x + y); // Hello Bello

let person = { name: 'Bello', isTrue: true }
let { name: lastName, isTrue: t } = person;

console.log(lastName); // Bello
/* console.log(name); // ReferenceError: name is not defined */

let user = { lName: 'Bello', id: '3kwe9i' };
let { lName = 'Doe', isTrue = false } = user;

console.log(lName); // Bello
console.log(isTrue); // false

Happy coding!


Buy me a Coffee


TechStack | Domain

  • Purchase a .com domain name as low as $9.99.
  • Purchase a .net domain name as low as $12.99.
  • Get cheaper domain names as low a $3.
  • Build a website with ease.

JavaScript

Part 30 of 50

You will learn the basics of JavaScript, including the Modern JS or *ECMAScript 2015+* The approach is from the basics to more advanced topics with lots of examples. It also include YouTube videos...

Up next

JavaScript Object Getter and Setter Methods

Getter Getter methods are used to return an object's properties. See the examples below: const person = { name: 'Bello', age: 27, getPerson() { if (typeof this.name === 'string' && typeof this.age === 'number') { return `${this.name}...