Introduction
There are different ways to phrase conditional logic. If we have a
certain condition, let’s do this, else, let’s do that. This is the
typical logic that guides conditional logic, and basically the if/else
statement. However, we can always expand the way we work around the
if/else statement with other Boolean operators such as not, and,
etc.
To negate code in JavaScript, we can make use of the JavaScript
logical NOT or Negate (!) operator, and in this article, we will discuss
how to achieve this and write if not code.
The NOT (!) operator
The NOT (!) operator, when applied on an operand, reverses the
Boolean value. For example, it changes true to false, and
vice-versa. It is considered a negation.
Let’s see the NOT operator at work
console.log(!false);
console.log(!(13 > 10));
Output
true
false
The first log statement shows the NOT operator reversing the false
value to true. In the second log statement, the comparison statement
is first executed to true, and then the NOT operator reverses the
true value to false.
Using if not for conditional logic
In conditional logic, we can make use of logical operators such as the
NOT operator. So in certain scenarios, we might need to negate the
condition for a simpler code. Therefore, with the use of the NOT
operator, we can negate the if statement.
For example, we write a code to check if isActive is true, log
active, and log not active, if otherwise.
let isActive = true;
if (isActive) {
console.log("active");
} else {
console.log("not active");
}
Output
active
However, if we only need to log a not active statement and not the
active statement. So there is no way for us to log the not active
without having to change the conditional logic. That’s where a if not
statement comes in. With a if not statement, we will not need to have
a else statement. Then, the NOT operator negates the isActive
Boolean value to false which is the condition for the not active
statement.
let isActive = true;
if (!isActive) {
console.log("not active");
}
Output
not active
Summary
If you want to negate a if statement, we can do so using the NOT
operator which reverses the Boolean value, and so changes it from true
to false or from false to true.
References
Logical NOT (!) - JavaScript | MDN
(mozilla.org)
How
to negate code in “if” statement block in JavaScript -JQuery like ‘if
not then..’

![Using not (!) inside 'if' statement in JS [SOLVED]](/javascript-if-not/javascript-if-not.jpg)