DEV Community

Discussion on: Improve your JS skills with those tips #2

Collapse
 
manoharreddyporeddy profile image
Manohar Reddy Poreddy • Edited
const condition = true
const other = {
   other: 'other',
   ...condition && { name: 'toto' }
}
Enter fullscreen mode Exit fullscreen mode

is it destructing of boolean variable?
can you help point from where you learnt this? MDN/other?
Thanks

Collapse
 
codeoz profile image
Code Oz

hey I'm looking for the article that explain it! Share it after ;D

Collapse
 
codeoz profile image
Code Oz

I will divide the answer in two parts to be more clearly!

First it's not destructing but spread operator.

When you use spread for example -> const toto = { ...anotherObject } it's a shortcut of const toto = Object.assign({}, anotherObject)

Js engine will check all enumerable property (it's like when you make a for...in loop on an object or Object.entries()), for example -> Object.entries(anotherObject) and put all key/value to the new object!

So now let's get the example from the article.

In case of condition is true, JS engine will check the expression, and see that condition is true so it will go to { name: 'toto' }. And then we add all property from this object (here name: toto) to the other object.

In case of condition is false, JS engine will try to do this Object.assign({}, condition) but condition is a boolean, not an object! So it will convert it (in really case wrapping it) to an object like this new Boolean(false). So it will create a boolean object, but this boolean object don't have any enumerable properties! So Js will make this Object.entries(booleanObject) = [] so it add 0 property to the new object!

It not really easy to understand, I will take another example

Imagine this code const toto = { ...'hello' } JS Engine will make this Object.assign({}, new String('hello')) when you make Object.entries(new String('hello')) you will have a list of all value key/pair, and with a string object you will have a value for each char, so JS engine will add all property (except length) to the new object so we will have toto = {0: 'h', 1: 'e', 2: 'l', 3: 'l', 4: 'o'}