DEV Community

loading...
Cover image for JavaScript Destructuring Assignment - 1

JavaScript Destructuring Assignment - 1

bello profile image Bello Updated on ・2 min read

image.png


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.`);
Enter fullscreen mode Exit fullscreen mode

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

Syntax:

const { key } = obj;
console.log(key);
Enter fullscreen mode Exit fullscreen mode

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.`);
Enter fullscreen mode Exit fullscreen mode

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.`);
Enter fullscreen mode Exit fullscreen mode

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

Syntax:

{ childObjNKey } = parentObj.childObj1.childObj2...childObjN;
childObjNKey;
Enter fullscreen mode Exit fullscreen mode

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.`);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (0)

pic
Editor guide