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
Selected Reading
Is the !! (not not) operator in JavaScript equivalent to reverse process of not operator?
Yes, the !! (not not) operator is the reverse process of the ! (not) operator. The single ! converts a value to its opposite boolean, while !! converts any value to its boolean equivalent.
How the Not Operator Works
The single ! operator converts truthy values to false and falsy values to true:
var flag = true;
console.log("Original value:", flag);
console.log("Single ! result:", !flag);
Original value: true Single ! result: false
How the Not Not Operator Works
The !! operator applies ! twice, effectively converting any value to its boolean equivalent:
var flag = true;
console.log("Original value:", flag);
console.log("Double !! result:", !!flag);
Original value: true Double !! result: true
Complete Example
var flag = true;
console.log("The result of single ! =");
console.log(!flag);
console.log("The result of double !! =");
console.log(!!flag);
// Testing with different values
console.log("\nTesting with different values:");
console.log("!!'hello':", !!"hello");
console.log("!!0:", !!0);
console.log("!!null:", !!null);
console.log("!!undefined:", !!undefined);
The result of single ! = false The result of double !! = true Testing with different values: !!'hello': true !!0: false !!null: false !!undefined: false
Common Use Cases
The !! operator is commonly used to convert values to boolean type explicitly:
function hasValue(input) {
return !!input; // Converts to boolean
}
console.log(hasValue("text")); // true
console.log(hasValue("")); // false
console.log(hasValue(42)); // true
console.log(hasValue(0)); // false
true false true false
Conclusion
The !! operator is indeed the reverse of ! ? it converts any value to its boolean equivalent. Use !! when you need explicit boolean conversion instead of relying on JavaScript's automatic type coercion.
Advertisements
