JavaScript double bang !! (double negation)

If you read enough JavaScript code, you will find code like this:

var x = !!'';
console.log(x); // false

The double bang !! looks like a logical operator, but it's not.

It's the logical not (!) used twice. The !! converts a value to a boolean.

Look what happens in the code below:

console.log(!!''); // false

// The code above is similar to these steps:
// 1. !!false // empty string "" is converted to false
// 2. !true
// 3. false

You can also use the Boolean function to do equivalent conversions.

!!''; // false
Boolean(''); // false, Boolean is the same as !!

Should you learn Boolean and !!? Yes, they can be seen in many codebases.

Which one is faster? Boolean or !!? You might think on optimizing this and check jsperf. This is micro benchmarking and usually it's not good. Check this great talk to understand why.

Which one should you use? It seems to be personal preference. Some people find !! more obscure, some find it more succinct.

Check more examples in the questions section. Learn more about unexpected truthy values.

Questions

What's the output?

!!0;

What's the output?

!!null;

What's the output?

!!NaN;

What's the output?

!!undefined;

What's the output?

!!false;

What's the output?

//prettier-ignore
!!"";

What's the output?

!!'false';

What's the output?

!!Boolean(false);

What's the output?

!!new Boolean(false);