JavaScript

How to Use OR Condition in a JavaScript IF Statement?

The such logical operator that returns a true value if one of the expressions/conditions is true is known as OR operator. On the other hand, it will be false, when both provided expressions/conditions are not true. It is often used with an if statement to execute a certain block of code if one or more conditions are met. The OR operator is symbolized by two vertical lines (||). It has a lower precedence than the AND operator (&&), which means that it is evaluated after the AND operator.

In this post we will explain the usage of the OR condition in JavaScript “if” statement.

Usage of OR Condition in IF Statement

The OR (||) operator is utilized in if statement. This operator will evaluate to true if either of the conditions it is comparing is true.

Syntax

Follow the given syntax for using OR condition in the if statement:

if (condition1 || condition2) {
// do something
}

Or you can compare one or more operands with each other using the OR operator in the if statement:

if (condition1 || condition2 || condition3 || condition4) {
// do something
}

It will return true if any of the conditions are true.

Truth Table of OR Operator in JavaScript

Let’s check out the truth table of the OR operator:

x y x||y
true true true
false true true
true false true
false false false

The truth table demonstrates that the OR operator will produce the result “true” if any of the variable values are “true”. When both values of “x” and “y” are “false”, it outputs “false”.

Example

Create a variable “a” and store a number “15”:

var a = 15;

Now, use the OR condition to verify the number stored in “a” is greater than 10 and less than 20. If any one of the provided condition is true (i.e., either “a” is less than 20 OR “a” is greater than 10), this statement will execute:

if(a < 20 || a > 10) {
console.log("The value of a is between 10 and 20");
}

Output

That was all about using the OR condition in JavaScript IF statement.

Conclusion

For using the OR condition in JavaScript “if” statement, utilize the OR operator denoted by two vertical lines (||). This operator outputs true if one of the expressions/conditions is true and false when both are not true. This article described the usage of the OR condition in the “if” statement in JavaScript.

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.