Syntax error What is the !! (not not) operator in JavaScript?

What is the !! (not not) operator in JavaScript?



In this article, we will learn about the !! (not not) operator in JavaScript.This double negation forces a value to be evaluated as either true or false.

What is the !! Operator?

The double negation(!! ) operator is the! Operator twice and calculates the truth value of a value. It returns a Boolean value, which depends on the truthiness of the expression. 

How It Works:

  • The first ! negates the value, converting it to true or false.
  • The second ! negates it again, effectively converting it into a strict boolean (true or false).

Consider (!!p) as !(!p), here's an example ?

If p is a false value, !p is true, and !!p is false.
If p is a true value, !p is false, and !!p is true.

Truthy and Falsy Values

In JavaScript values are inherently truthy or falsy when evaluated in a boolean context. The !! operator uses this behavior to convert any value to true or false.

Falsy Values ?

false
0
"" (empty string)
null
undefined
NaN

All other values are considered truthy.

Example

Below is an example for the !! (not not) operator in JavaScript ?

console.log(!!"Hello");  
console.log(!!0);        
console.log(!!null);     
console.log(!![]);       
console.log(!!{});    

Output

true
false
false
true
true

Example

conditional statements or when passing a value to a function that expects a boolean ?

let input = "";

if (!!input) {
    console.log("Input has a value.");
} else {
    console.log("Input is empty."); // This will execute
}

Output

Input is empty.

Conclusion

The !! operator is a simple yet powerful way to convert any value to a boolean in JavaScript. It is especially useful when working with conditional logic checking variable existence, and ensuring valid data.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-02-20T18:26:10+05:30

616 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements