DEV Community

Cover image for ๐Ÿš€Using !! in Javascript
Yuli Petrilli
Yuli Petrilli

Posted on • Updated on

๐Ÿš€Using !! in Javascript

In JavaScript, the "not not" operator, also known as the double negation operator, is denoted by two exclamation marks (!!). It is a unary operator that converts any value to its corresponding boolean value.

How itย Works?

Well, theย !! operator works by first converting the operand (your value) into a boolean. It then negates this value and negates it again, resulting in a boolean that reflects the truthiness of the original value.

Let's take a look at the following example:

let x = 5;
let y = !!x;
console.log(y); // true
Enter fullscreen mode Exit fullscreen mode

Here, the value of x is first converted to a boolean, and since x is a non-zero number, it is truthy, so the first negation results in false. The second negation then negates this value again, resulting in true.

Practical Uses

Let's take a look at the following example:

let username = "";
if (!!username) {
  console.log("Welcome, " + username);
} else {
  console.log("Please enter a username");
}
Enter fullscreen mode Exit fullscreen mode

Here, theย !! operator is used to check if the username variable is truthy or falsy. If it is falsy (in this case, an empty string), the else block is executed, prompting the user to enter a username. If it is truthy, the if block is executed, welcoming the user with their username.

Wanna try it yourself? What would the result of the following expressions:

!![]
!!{}
!!null
!!"foo"
!!-1

Conclusion ๐Ÿ

Unless you have been using JavaScript for a while this will probably look like some advanced magic but a quick way to remember this is that, !! it's just a shorthand way to convert any value to a boolean.

This operator is a powerful and it can be particularly useful when dealing with certain validations, also, it is a definition commonly asked nowadays in interviews so make sure to keep it present (also, using it will make you look cool).

Happy learning and thank you for reading!

If this article was helpful to you, don't forget to hit that โค๏ธ button and support me with a follow, i will keep posting more content about tech, programming, career development and more! :)

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ • Edited

Sorry to tell you this, but Javascript has no !! operator, you're just using the logical NOT (or negation) operator twice.

console.log(!!1)  // true
console.log(! ! 1)  // true
console.log(!            !1)  // true
Enter fullscreen mode Exit fullscreen mode

Also, in your use case the code would work equally well (and would probably be more efficient, and readable) if you removed !! entirely.