What Does Double Negation (!!) Do in JavaScript?

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');

Scammers and spammers hate Aura - and that's a good thing for you

Aura logo
Are you tired of unwanted emails, texts, and calls from scammers and spammers? Aura uses cutting-edge AI technology to scan the internet to identify where your personal information is exposed and being sold. With Aura, you can take control of your online privacy and secure your personal information. Reduce robocalls and keep your information safe from identity thieves. Try Aura free for 2 weeks and see if your information has been compromised.

11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *