Home > Mobile >  Why does destructuring on boolean is working in javascript?
Why does destructuring on boolean is working in javascript?

Time:09-25

why destructuring a boolean is working. For example

const condition = true
const toto = { name: 'toto' }

const other = {
   other: 'other',
   ...condition && toto
}
console.log({ other }) // { other: 'other', name: 'toto' }

const falseCondition = false

const otherWithoutToto = {
   other: 'other',
   ...falseCondition && toto
}

console.log({ otherWithoutToto }) // { other: 'other' }

In the case of false boolean, we don't add property, otherwise we will. Actually it's working well but someone can explain me why is it possible?

CodePudding user response:

What you're using here isn't destructuring, it's object property spread. It requires that the expression to the right-hand side (RHS) of the ... evaluates to either an object or something that can be converted to one (with exceptions for null and undefined). It then takes the own-enumerable properties from the object and copies them to the object being created. In the case of your example, two possibilities can occur for the below code:

...(condition && toto)
  1. condition is true, and so the above expression evaluates to the object toto. It doesn't evaluate to a boolean, but rather the last truthy value, which in your case is the object toto. The object property spread syntax then takes the own-enumerable properties from the object and adds them to the object being created.

  2. condition is false, and so the above expression evaluates to the value false. This means that JavaScript treats the above code as ...false. As false is a primitive and not an object, JavaScript tries to convert it to one by wrapping it in a boolean object:

    ...new Boolean(false)
    

    now that the RHS of the ... has been converted to an object, JavaScript then takes the own-enumerable properties of the boolean object and adds them to the object being created. As the boolean doesn't have any own properties which are enumerable, nothing is added to the created object.

CodePudding user response:

As everyone said, this isn't destructuring but spread. In fact, all it does is making an Object.assign({}, item).

If you take a look at the documentation, the Object.assign() method copies all enumerable own properties to a target object.

Since boolean (as number) aren't enumerables, these aren't copied. It just returns the object without the new properties.

Documentation link : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

You can try console.log({ ...'str' }) or in ES5 console.log(Object.assign({}, 'str')), since strings are enumerables it returns { 0: 's', 1: 't', 2: 'r' }.

  • Related