DEV Community

Discussion on: Destructuring in JavaScript

Collapse
 
okbrown profile image
Orlando Brown • Edited

Hi, I'm not sure about this... Please explain how this works.

const mood = {
   ...isWeekend ? {} : {}
}

How does one spread a Boolean?
Should this not be

const mood = {
   isWeekend ? ...{} : ...{}
}
Collapse
 
mahmoudelmahdi profile image
Mahmoud Elmahdi • Edited

the isWeekend flag holds a boolean value (which is condition not the key), and based on that we decide which key property (music or routine) to add to the mood object, and since the Spread operator (three dots ...) allows us to add/concat things into object and array literals that was the point of using it! is to add the desirable key conditionally.

If you try to execute your second snippet

const mood = {
   isWeekend ? ...{} : ...{}
}

You'll get syntax error.

I create a demo for the same logic in ES6 and its equivalent in ES5.

I hope that answers your question.