support@90-10.dev

JavaScript Logical Operators

Logical Operators are used to combine two or more conditions together and return a single output based on the conditions.

AND Operator

The AND (&&) operator returns true only if all the conditions are true:

let x = 5;
let y = 10;
if (x > 0 && y > 0) {
    console.log("Both x and y are positive");
}

The && operator uses short-circuit evaluation - the second operand will only be evaluated if the first operand is true. If the first operand is false, the second operand will not be evaluated because the overall result of the expression will always be false. This can be useful in situations where the second operand could cause an error if it was evaluated when the first operand is false.

let x = null;

if (x !== null && x.length > 5) {
  console.log("The string is long enough");
}

OR Operator

The OR (||) operator returns true if at least one of the conditions is true - it is often used to create a condition that is true if any one of a set of conditions is true:

let age = 25;
if (age < 18 || age > 60) {
    console.log("You are not eligible for this job");
}

The || operator also uses short-circuit evaluation. - the second operand will only be evaluated if the first operand is false, because if the first operand is true, the overall result of the expression will always be true. This behavior can also be useful in situations where we want to provide a default value if a variable is undefined or null.

let x = null;
let y = x || "default value";

console.log(y);  // prints: "default value"

NOT Operator

The NOT (!) operator is used to reverse the logical state of its operand - it is often used to create a condition that is true if a specific condition is not met:

let loggedIn = false;
if (!loggedIn) {
    console.log("Please login to continue");
}


Take Away

The 3 logical operators - &&, || and ! - are used extensively in JavaScript programming to make complex decisions based on multiple conditions. By combining conditions using logical operators, you can create powerful expressions that enable your code to make decisions based on a variety of circumstances.