You might have seen the double negation operator (!!) used in some JavaScript code. What is its function?
Double negation converts truthy values to the true Boolean and falsy values to the false Boolean. It is not a distinct JavaScript operator, but really just a sequence of two negations. Apply the first negation results in false for a truthy value, and true for a falsy value. The second negation will then operate on the normal Boolean value that results.
Here is an example:
!!2; // -> true
!!''; // -> false
!!NaN; // -> false
!!'word'; // -> true
!!undefined; // -> false
Note: If you need to convert a value to a Boolean, it’s better to be explicit and use the Boolean constructor instead of double negation. We could have more clearly written the above example as:
Boolean(2); // -> true
Boolean(''); // -> false
Boolean(NaN); // -> false
Boolean('word'); // -> true
Boolean(undefined); // -> false
Note: We don’t need to convert a value to a Boolean to check if it is truthy or falsy in ternary operators or if statements. We can use the value directly:
if (2) console.log('executed');
if ('') console.log('NOT executed');
if (NaN) console.log('NOT executed');
if ('word') console.log('executed');
if (undefined) console.log('NOT executed');
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.
