Last updated on September 21, 2023
Logical operators are primarily used in JavaScript to perform logical operations on boolean values, TRUE and FALSE. Let’s suppose we have requirements where we need to apply two or more conditions within a single statement. To do that we use logical operators in JavaScript.
Look at the below table that contains logical operators with their symbols, names, and operations.
Operator | Name | Operation |
&& | AND | returns true if both the operands are true else false |
|| | OR | returns true if either of the operands is true else false |
! | NOT | returns true if let x is false |
Return value: The logical operators return a boolean (either true or false).
Below are the examples of logical operators.
01. Logical AND(‘&&’) Operator:
The AND operator returns true if both variable’s comparisons are true.
let schoolBag = 12;
let books = 10;
if (schoolBag == 12 && books == 10) {
console.log('this block will be running...');
}
// output: this block will be running...
In this example, we have two variables schoolBag and books that store different integer values. We are checking both variables through the if-statement by using the AND logical operator.
Since both conditions are true in this case, the code within the if block will execute, and the message “This block will be running…” will be logged to the console.
2. Logical OR (||) Operator:
The OR operator returns ‘true’ in the result when at least one of the conditions is true.
let obtainedMarks = 610;
let passingMarks = 550;
let attemptedAllQuestions = true;
if (obtainedMarks > passingMarks || attemptedAllQuestions) {
console.log('this block will be executing');
}
// output: this block will be executing
In this example, we have two variables that defining student’s attempt of solving all the questions and obtained marks. Then in the if statement we are checking if the obtained marks are greater than passing marks or if the student attempted all the questions through the OR operator.
3. NOT (!) Operator:
The NOT operator checks if the condition is not true.
let isSchoolOffToday = true;
if (!isSchoolOffToday) {
console.log("School is open.");
}else{
console.log("Yes, today is off.");
}
// output: Yes, today is off.
In above example, we have a variable isSchoolOffToday that stores true value. In the next line of code, we are checking if the variable is not true through the NOT (!) operator.
As we set the variable isSchoolOffToday to true, when we use !isSchoolOffToday, it means ‘Is it NOT true?’ In this case, since it is true, ‘NOT true’ is false. So, we go into the ‘else’ part and say, ‘Yes, today is off.
Conclusion:
In this article we explained JavaScript logical operators AND, OR and NOT along with their examples.