Logical Operations in JavaScript

Logical Operatore in JavaScript

Logical operators in JavaScript are used to perform logical operations on Boolean values. These operators allow you to combine or manipulate Boolean values to make decisions in your code.

Here comes the main Logical operators used in JavaScript

Logical AND (&&)

This will return true if both operands are true.

Example as follows

var a = true;
var b = false;

var result = a && b;  // result is false

Here both a and b are not true so the value of result will be False.

Logical OR (||)

This will return true if at least one of the operands is true.

Example as follows

var a = true;
var b = false;

var result = a || b;  // result is true

Here either a or b is true so the value of result will be true.

Logical NOT (!)

This will return true if the operand is false, and false if the operand is true.

Example as follows

var a = true;

var result = !a;  // result is false

These logical operators are often used in conditional statements and expressions to make decisions based on certain conditions.

Example Using Logical AND (&&)

var age = 25;
var hasLicense = true;

if (age >= 18 && hasLicense) {

    console.log("You are eligible to drive.");
} else {

    console.log("You are not eligible to drive.");

}

Example Using Logical OR (||)

var temperature = 28;

if (temperature < 0 || temperature > 30) {
    console.log("Extreme weather conditions.");

} else {
    console.log("Weather conditions are normal.");

}

Example Using Logical NOT (!)

var isLoggedOut = true;

if (!isLoggedOut) {
    console.log("User is logged in.");

} else {
    console.log("User is not logged in.");

}

Also note that, logical operators are fundamental in control flow and decision-making in JavaScript, allowing you to create flexible and responsive code based on different conditions.