JavaScript

How to Negate Code in “if” Statement Block in JavaScript

Negating code in an “if” condition block in JavaScript is a way to change the condition’s logic so that it will only execute when the opposite of the original condition is true. This can be done by utilizing the logical “Not” (!) operator before the conditional statement.

This blog will demonstrate the process of negating the code in JavaScript if statement.

How to Negate Code in JavaScript’s “if” Statement Block?

In JavaScript, you can negate a code block in an if statement by using the “Logical NOT (!)” operator. The NOT (!) operator negates the boolean value of an expression, so if you place it before a condition, it will invert the truthiness of that condition.

Syntax

For negating code in an if statement, use the given syntax:

if(!condition){
 // do something
}

 
Example 1: Negate a Boolean Value in “if” Statement Block

Create a variable “isTrue” that stores a boolean value “true”:

var isTrue = true;

 
Use the NOT operator in the if statement that will check and execute when the condition is false. Here, we will print “false” on the console by negating the value of the variable “isTrue” that is true. Else, print “true”:

if(!isTrue){
 console.log('false');
}
else{
 console.log('true');
}

 
The output display “true” on the console because in the if statement, we will check if the variable “isTrue” is false print the “false” else, print “true”:


Example 2: Negate any Condition in “if” Statement Block

You can also negate any condition in the “if” statement block using the NOT operator. First, create a variable “x” that stores the number “15”:

var x = 15;

 
Now, in the if statement, we will check if “x” is not greater than 10, then it is less than or equal to 10. Else, x is greater than 10:

if (!(x > 10)) {
 console.log("x is less than or equal to 10");
} else {
 console.log("x is greater than 10");
}

 
Output


That’s all about negating the if statement block in JavaScript.

Conclusion

To negate code in the JavaScript’s “if” statement block, use the “Logical NOT (!)” operator. It will invert the value or result of the specified condition. In this blog, we demonstrated the process of negating the code in JavaScript’s “if” statement.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.