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;
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With