Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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.
Basic Examples
Below is an example for the !! (not not) operator in JavaScript:
console.log(!!"Hello"); // String is truthy
console.log(!!0); // 0 is falsy
console.log(!!null); // null is falsy
console.log(!![]); // Empty array is truthy
console.log(!!{}); // Empty object is truthy
true false false true true
Using !! in Conditional Statements
The !! operator is useful in 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
}
// Another example with undefined variable
let userData;
console.log("User data exists:", !!userData);
Input is empty. User data exists: false
Common Use Cases
The !! operator is commonly used when:
- Converting user input to boolean for validation
- Checking if variables exist before using them
- Creating clean boolean flags from complex expressions
- Ensuring function parameters are proper boolean values
Conclusion
The !! operator is a simple yet powerful way to convert any value to a boolean in JavaScript. It leverages JavaScript's truthy/falsy nature to provide clean boolean conversion for conditional logic and data validation.
