JavaScript features the odd but commonly used double negate operator !!, which is used to create a Boolean from a value.

For example, consider the code below, which returns True because there is a value (a string) for the variable foo.

var foo = 'hello';
var baz = !!foo;
baz; // true

But there is no !! operator, just the logical NOT or negate operator, !, used twice.

Negate operator

The negate operator ! works in a two-step process:

  1. if the value passed is not already a Boolean, coerce it into a Boolean
  2. flip the pairing to negate it

By adding a second negate operator we merely flip the sign back since our value is already a Boolean thanks to the first !.

This is a horribly confusing pattern in JavaScript. Don’t do this even though you’ll probably see it in lots of open source code.

There is a better way.

Boolean object

Use the much more explicit Boolean object.

var foo = 'hello';
var baz = Boolean(foo);
baz; // true

So much better! Problem solved.

Want to improve your JavaScript? I have a list of recommended JavaScript books.