Logical Operator - 06

When operators work with booleans, true or false are called logical operators. 
There are three logical operators:

  • the and operator (&&)
  • the or operator (||)
  • the not operator, otherwise known as the bang operator (!)


The "and" operator (&&):

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

When both values of the condition are true, it will execute or run inside the if statement. If any of the values of the condition is false, it will not execute the codes of block or block statement of if statement. If the first value is false, then it will check the second value.

The "or" operator (||):

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

If any of the values of the condition becomes true, then it will execute or run the codes of the block or block statement inside the if statement. When both the values are false, it will not execute the code inside the if statement.

the "not" or "bang" operator

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

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

If so! the operator takes the true value, and it will pass back the false value. Or, if so! the operator takes the false value, and it will pass back the true value. 


Note Book ===> 

OR operator(||):

If we use "or" operator outside the condition like if condition, then it will behave as

const val = true;
 function myFunc() {
   console.log("Function runs");
 }
 
console.log("Function not runs")
val || myFunc();

This will print “Function not runs” because the first value is true and it will not go to call the function myFunc. 
If the first value is false, then the second value (right side of or operator) will execute.

AND operator(&&):

If we use "AND" operator outside the condition like if condition, then it will behave as…

const val = true;
function myFunc() {
   console.log("Function runs");
 }
console.log("Function not runs")
val && myFunc();

This will print “Function runs” because the first value is true and it will go to call the function myFunc.
If the first value is false, then the second value (right side of or operator) will not execute.


Post a Comment

Previous Post Next Post