How to Use the Logical OR Operator (||) in JavaScript?

Estimated read time 2 min read

The logical OR operator (||) is used in JavaScript to evaluate two expressions and return true if either one of them is true, or false if both expressions are false. Here’s an example of how you could use it:

let result = expression1 || expression2;

Here, expression1 and expression2 are any valid JavaScript expressions that return a boolean value (true or false). The result variable will be assigned the value of expression1 if it’s true, or expression2 if expression1 is false.

For example:

let firstName = 'John';
let lastName = '';
let fullName = firstName || lastName || 'Unknown';
console.log(fullName);

In this example, the fullName variable will be assigned the value of firstName ('John'), because firstName is true (i.e., it’s a non-empty string). If firstName were '' (an empty string), the fullName variable would be assigned the value of lastName, and if lastName were also an empty string, the fullName variable would be assigned the value 'Unknown'.

The logical OR operator is often used to provide a default value for a variable, or to make sure that a value is within a certain range. For example:

let age = 25;
let minAge = 21;
let isAdult = (age >= minAge) || false;
console.log(isAdult);

In this example, the isAdult variable will be assigned the value true, because age is greater than or equal to minAge. If age were less than minAge, the isAdult variable would be assigned the value false.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply