DEV Community

brajeshkanungo
brajeshkanungo

Posted on

JavaScript Destructuring

Destructuring?

Destructuring decouples arrays, and objects and assign in it the variables. Help us to write clean and readable code.

Where we can apply Destructuring?

  1. Arrays
  2. Objects

1. Arrays Destructuring

const weekdays = [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
const oceans = ['Arctic Ocean','North Atlantic Ocean',
'South Atlantic Ocean','Indian Ocean','North Pacific Ocean',
'South Pacific Ocean','Southern Ocean']
Enter fullscreen mode Exit fullscreen mode

Accessing array items with the index value manually

const weekdays = [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
let mon = weekdays[0];
let tue = weekdays[1];
let wed = weekdays[2];
console.log(mon, tue, wed) // Monday, Tuesday, Wednesday
Enter fullscreen mode Exit fullscreen mode

Applying destructuring to access array items

const oceans = ['Arctic Ocean','North Atlantic Ocean',
'South Atlantic Ocean','Indian Ocean','North Pacific Ocean',
'South Pacific Ocean','Southern Ocean']

const [ocean1, ocean2, ocean3] = oceans
console.log(ocean1, ocean2, ocean3) // Arctic Ocean,North Atlantic Ocean,South Atlantic Ocean
Enter fullscreen mode Exit fullscreen mode

2. Objects Destructuring

The following methods used to access value of an object:

1. Using the Dot ( . ) 

const myCar = {
    make: 'Ford',
    model: 'Mustang',
    year: 1969,
    color: 'Black'
};


let manufacturer = myCar.make;
let model = myCar.model;

console.log(manufacturer, model) // Ford, Mustang

2. With Angle bracket Object[key_name]

let year = myCar[year]
let color = myCar[color]

console.log(year, color) // 1969, Black
Enter fullscreen mode Exit fullscreen mode

When we destructure an object the name of the variable should be exactly the same as the key or property of the object. See the example below.

const myCar = {
    make: 'Ford',
    model: 'Mustang',
    year: 1969,
    color: 'Black'
};

let {manufacturer, model, year, color } = myCar
console.log(manufacturer, model year, color) // Ford, Mustang, 1969, Black
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
developerkaren profile image
Karen Efereyan

This Is beautiful