Hone

Lessons · JavaScript · !! makes a boolean

Forcing a boolean

!!x converts any value to true or false by negating twice. It is the same conversion as Boolean(x).

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

A function documented to return a boolean should not return a string or an object that happens to be truthy. !! makes the type honest.

How to think about it

Use !! or Boolean() to normalise, never to validate: it reports truthiness, and '0' is truthy. Validate with the real test first.

Worked example

console.log(!!"false");
true: a non-empty string is truthy.
console.log(!!0, !!"");
false false.
console.log(!!{}, Boolean({}));
true true: !! and Boolean() are the same conversion.

Your turn

A boolean for whether the list has items.

const hasItems = items.length;

The trap

!!'false' is true. Double-bang does not parse text; it asks whether the value is truthy.

Practise !! makes a boolean on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.