JavaScript: Anything to boolean

6/4/2016javascript, tipsCody ReichertBack to blogs

Double negatives aren't not bad, but the Logical NOT operator is pretty cool. You're probably familiar with it, !. It's a unary operator that returns false if it's argument can be coerced to true, and vice versa:

    !true // false
    !false // true

    // with coercion
    !1 = // false
    !0 = // true
    ![] = // false

And since ! returns a single boolean, we can pass it's result to another !: !!:

    !!true // true
    !!false // false

    // with coercion
    !!1 = // true
    !!0 = // false
    !![] = // true

You should know the rules of what can be converted to true (truthy) and to false (falsy).

Blog comments powered by Disqus.