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
Explain about logical not(!) operator in detail with example in javascript?
The logical NOT operator (!) is a unary operator that inverts boolean values. It returns true for falsy values and false for truthy values.
Syntax
!expression
How It Works
The NOT operator first converts the operand to a boolean value, then returns its opposite:
- If the operand is truthy, it returns
false - If the operand is falsy, it returns
true
Example with Boolean Values
<html>
<body>
<p id="boolean-demo"></p>
<script>
document.getElementById("boolean-demo").innerHTML =
"!true = " + !true + "<br>" +
"!false = " + !false;
</script>
</body>
</html>
!true = false !false = true
Example with Comparison Operators
<html>
<body>
<p id="comparison-demo"></p>
<script>
var x = 200;
var y = 300;
document.getElementById("comparison-demo").innerHTML =
"x < y = " + (x < y) + "<br>" +
"!(x < y) = " + !(x < y) + "<br>" +
"x > y = " + (x > y) + "<br>" +
"!(x > y) = " + !(x > y);
</script>
</body>
</html>
x < y = true !(x < y) = false x > y = false !(x > y) = true
Example with Falsy and Truthy Values
<html>
<body>
<p id="falsy-demo"></p>
<script>
document.getElementById("falsy-demo").innerHTML =
"!0 = " + !0 + "<br>" +
"!'' = " + !'' + "<br>" +
"!null = " + !null + "<br>" +
"!undefined = " + !undefined + "<br>" +
"!NaN = " + !NaN + "<br>" +
"!'hello' = " + !'hello' + "<br>" +
"!42 = " + !42;
</script>
</body>
</html>
!0 = true !'' = true !null = true !undefined = true !NaN = true !'hello' = false !42 = false
Double NOT Operator (!!) for Type Conversion
The double NOT operator (!!) is commonly used to convert values to boolean:
<html>
<body>
<p id="double-not-demo"></p>
<script>
document.getElementById("double-not-demo").innerHTML =
"!!'hello' = " + !!'hello' + "<br>" +
"!!0 = " + !!0 + "<br>" +
"!![] = " + !![] + "<br>" +
"!!{} = " + !!{};
</script>
</body>
</html>
!!'hello' = true
!!0 = false
!![] = true
!!{} = true
Common Use Cases
- Conditional Logic: Inverting boolean conditions in if statements
- Input Validation: Checking if required fields are empty
-
Type Conversion: Converting values to boolean using
!! - Negating Expressions: Making code more readable by negating complex conditions
Conclusion
The logical NOT operator (!) is essential for inverting boolean values and working with falsy/truthy expressions. Use !! when you need explicit boolean conversion.
Advertisements
