Double negation is a common JavaScript trick that allow you to convert different types to boolean. Here’s how double negation works in JS.
Double negation consists of two exclamation marks written in a row.
const x = NaN;
const y = undefined;
const z = 0;
console.log(!!x); // false
console.log(!!y); // false
console.log(!!z); // false
You can apply double negation to any JavaScript variable and get the boolean that represents whether this variable is truthy or falsy.
Falsy variables in JS are:
false
undefined
null
NaN
+0
and-0
- an empty string
Everything else is considered a truthy value in JavaScript.
So, if you want to get a boolean representation of a “truthfulness” of any JS value, you apply double negation to it.
The first negation turns the provided value to boolean. The second one inverts this boolean.
Note that an empty object, and an empty array are considered truthy in JavaScript (contrary to an empty string).
const emptyObject = {};
const emptyArray = [];
const emptyString = '';
console.log(!!emptyObject); // true
console.log(!!emptyArray); // true
console.log(!!emptyString); // false