JavaScript Boolean operators allow you to perform different comparisons on the specified variables and evaluate the results. Here is the list of Boolean operators supported by JavaScript:
- Boolean OR “||” operator
- Boolean AND “&&” operator
- Boolean NOT “!” operator
OR operator
It is represented using the double pipe operator “||”.
result = x || y
OR behaves as described in the following truth table:
x | y | x || y |
true | true | true |
true | false | true |
false | true | true |
false | false | false |
AND operator
It is represented by using a double ampersand “&&” sign.
result = x && y
AND behaves as described in the following truth table:
x | y | x && y |
true | true | true |
true | false | false |
false | true | false |
false | false | false |
NOT operator
it is represented by an exclamation mark “!”.
var result = ! x;
Based on the values of the “x” variable, the corresponding “!x” will work as follows:
x | !x |
undefined | true |
null | true |
NaN | true |
Object {} | false |
Empty string “ “ | true |
Non-empty string | false |
Number other than 0 | false |
JavaScript Boolean operators examples
Simple example code.
<!DOCTYPE html>
<html>
<body>
<script>
// OR
let x = true, y = false;
var res = x || y;
console.log("OR ||", res);
// And
var res = x && y;
console.log("And &&", res);
// NOT
console.log("NOT", !x);
console.log("NOT", !y);
</script>
</body>
</html>
Output:
What Boolean operators can be used in JavaScript?
Answer: There are three operators: AND, OR, and NOT used as Boolean operators in JS. You can either in a database or in coding and come very handy to developers when building components of a complex logic or flow.
Do comment if you have any doubts or suggestions on this JS boolean topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version