Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring assignment vs object property access in ES6

what is the difference between var bmw = cars.bmw and var {bmw} = cars ? Which way is better?

var cars = {
    bmw: "M3",
    benz: "c250"
}

var bmw = cars.bmw // M3
var {bmw} = cars // M3

And I've seen people do this in Nodejs. Is it the same thing?

var {ObjectId} = require('mongodb')
var ObjectId = require('mongodb').ObjectID;
like image 676
RaxPat Avatar asked Jan 07 '18 12:01

RaxPat


People also ask

What is Destructuring assignment in ES6?

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

What is Destructuring assignment?

Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables.

What is difference between Destructuring and rest operator?

Destructuring is used to create varibles from array items or object properties. Spread syntax is used to unpack iterables such as arrays, objects, and function calls. Rest parameter syntax will create an array from an indefinite number of values.

What is Destructure property?

Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array​ at a time.


1 Answers

On bmw = cars.bmw you are assigning an object property to a variable, whereas var {bmw} = cars destructuring an object into given variables list.

As the result there is no difference (in your case), the bmw will have desired M3 value.

Moreover when destructuring the object you can list several variables to assign whilst = is 1-to-1 assignment where right part is being assigned to the left.


Also you can rename variable on destructuring like

const { bmw: BeeMWee } = cars;
like image 93
Paul T. Rawkeen Avatar answered Oct 13 '22 18:10

Paul T. Rawkeen