Skip to content
Related Articles

Related Articles

JavaScript Course | Logical Operators in JavaScript
  • Last Updated : 29 Apr, 2019

Previous article: JavaScript Course | Interaction With User
There are three logical operators in Javascript:

  • !(NOT)
  • &&(AND)
  • ||(OR)

!(NOT)
It reverses the boolean result of the operand (or condition).

result = !value;

The following operator accepts only one argument and does the following:

  • Converts the operand to boolean type i.e true/false
  • returns the flipped value

Example:




<script>
// !(NOT) operator
let geek = 1;
alert(!geek);
</script>

Output:



false

The operator converted the value ‘1’ to boolean and it resulted in ‘true’ then after it flipped(inversed) that value and that’s why when we finally alert the value we get ‘false’.

&&(AND)
The && operator accepts mutilple arguments and it mainly does the following:

  • Evaluates the operands from left to right
  • For each operand, it will first convert it to a boolean. If the result is false, stops and returns the original value of that operand.
  • otherwise if all were truthy it will return the last truthy value.
result = a && b; // can have mutiple arguments.

Example:




<script>
// &&(AND) operator
alert( 0 && 1 ); // 0
alert( 1 && 3 ); // 3
alert( null && true ); // null
alert( 1 && 2 && 3 && 4); // 4
</script>

Output:

0
3
null 
4

||(OR)
The ‘OR’ operator is somewhat opposite of ‘AND’ operator. It does the following:

  • evaluates the operand from left to right.
  • For each operand, it will first convert it to a boolean. If the result is true, stops and returns the original value of that operand.
  • otherwise if all the values are falsy, it will return the last value.
result = a || b;

Example:




<script>
// ||(OR) Operator
alert( 0 || 1 ); // 1
alert( 1 || 3 ); // 1
alert( null || true ); // true
alert( -1 || -2 || -3 || -4); // -1
</script>

Output:

1
1
true
-1

Next article: JavaScript Course | Conditional Operator in JavaScript

My Personal Notes arrow_drop_up
Recommended Articles
Page :