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:
<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
Recommended Posts:
- JavaScript Course | Operators in JavaScript
- JavaScript | Operators
- JavaScript | Bitwise Operators
- Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript
- JavaScript Course | Understanding Code Structure in JavaScript
- JavaScript Course | Printing Hello World in JavaScript
- JavaScript Course | Data Types in JavaScript
- JavaScript Course | Conditional Operator in JavaScript
- JavaScript Course | JavaScript Prompt Example
- JavaScript Course | Objects in JavaScript
- JavaScript Course | Loops in JavaScript
- JavaScript Course | Functions in JavaScript
- JavaScript Course | Variables in JavaScript
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- JavaScript | Let
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.



