Suppose we have objects car
and motorcycle
defined as follows:
const car = {
make: "Tesla",
weight: 3500
};
const motorcycle = {
make: "Harley",
registered_to: "John Smith"
};
Destructuring
From the Object car
, we can extract the value "Tesla"
under the key make
, and assign it to local variable make
like so:
let { make } = car;
console.log(make); // prints "Tesla"
But note that the syntax { make }
under the hood is actually shorthand for { make: make }
. Which leads us to...
Renaming
What if we want to take the value of "Tesla"
under the key make
, but assign it to a different variable, say manufacturer
?
let { make: manufacturer } = car;
console.log(manufacturer); // prints "Tesla"
Default
From our definition of the motorcycle
object, notice how there was no weight
key-value pair defined. What if we were to try to assign a default value of 1000
to the motorcycle
's weight, and assign it as the weight
variable?
let { weight = 1000 } = motorcycle;
console.log(weight); // prints 1000
But if weight
was defined like in the car
object, we are simply doing a destructure on car
.
let { weight = 1000 } = car;
console.log(weight); // prints 3500
All-in-one
Now, suppose we want to take car
and motorcycle
's registered_to
values, and store them in a variable owner
, and to have the value default to "Jane Doe"
if the key is missing. We can combine all 3 above techniques together in one line.
let { registered_to: owner = "Jane Doe" } = car;
console.log(owner); // prints "John Doe"
let { registered_to: owner = "Jane Doe" } = motorcycle;
console.log(owner); // prints "John Smith"
I hope this helps. I believe these one-liner approaches are what we call syntactic sugar. Please practice clean and readable code when applicable.
Top comments (0)