Hacker Read top | best | new | newcomments | leaders | about | bookmarklet login

Does JavaScript not have something like "bool(value)"?


view as:

You can use Boolean(value) but it will return an 'object' of a 'boolean' type, rather than a primitive boolean (it's one of JS's flaws so is generally avoided).

Note: their example of a similar piece of code is not identical, as it won't cast values like null to false. I think the best example of a clear equivalent would be:

    value = value ? true : false;

`Boolean(value)` returns a boolean primitive; `new Boolean(value)` returns a boolean object (which you never want).

Compare:

    > typeof Boolean(1)
    'boolean'
    > typeof new Boolean(1)
    'object'

In chrome console I get an object for new Boolean(false) but I think it is the primitive for Boolean(false), am I right or I missed something?

The !! mentioned in the article does exactly that.

Legal | privacy