JavaScript Course | Logical Operators in JavaScript

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

1
1
true
-1

Next article: JavaScript Course | Conditional Operator in JavaScript



My Personal Notes arrow_drop_up

Executive Software Developer at Cavisson Systems

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.