Logical Operators


Logical Operators

When logical operators are employed with Boolean (logical) values, they always return a Boolean value. However, because the && and || operators return the value of one of the specified operands; they may yield a non-Boolean result if they are used with non-Boolean values.

We'll be using booleans or true or false values when working with conditionals. The logical operators are operators in JavaScript that operate with boolean values. To make our conditionals more complicated, we may utilize logical operators. The following are the three types of logical operators:

the operator and (&&)

the not operator, also known as the bang operator (!) the or operator (||)

When we employ the && operator, we're ensuring that two conditions are met:

if (stopLight === 'green' && pedestrians === 0) {
console.log('Go!');
} else {
console.log('Stop');
}

Both conditions must evaluate to true for the whole condition to evaluate to true and execute when employing the && operator. If either condition is false, the && condition evaluates to false, and the else block executes.We may use the || operator if we just worry about one of the conditions being true:

if (day === 'Saturday' || day === 'Sunday') {
console.log('Enjoy the weekend!');
} else {
console.log('Do some work.');
}

OOnly one of the criteria must evaluate to be true for the whole statement to evaluate to true when employing the || operator.If either day === 'Saturday' or day === 'Sunday' evaluates to true in the code sample above, the if condition will evaluate to true, and the code block will run. The second condition in a || statement will not be tested if the first condition evaluates to true. Day === 'Sunday' will only be tested if day === 'Saturday' evaluates to false. Only if both comparisons evaluate to false will the code in the other expression run.

The boolean value of a boolean is reversed, or negated, with the! not operator:

let excited = true;
console.log(!excited); // Prints false

let sleepy = false;
console.log(!sleepy); // Prints true

Essentially, the!Operator accepts a true value and returns a false value, or it accepts a false value and returns a true value.

Example:

<html> <body> <h2>Knowledge2life</h2> <input id="age" value="18" /> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script> function myFunction() { let voteable; let age = Number(document.getElementById("age").value); if (isNaN(age)) { voteable = "Input is not a number"; } else { voteable = (age < 18) ? "Too young" : "Old enough"; } document.getElementById("demo").innerHTML = voteable + " to vote"; } </script> </body> </html>

OUTPUT:

Knowledge2life