1. JavaScript Booleans
Everything Without a “Real” is False
<script>
// The Boolean value of 0 (zero) is false:
var x = 0;
Boolean(x); // returns false
// The Boolean value of -0 (minus zero) is false:
var x = -0;
Boolean(x); // returns false
// The Boolean value of "" (empty string) is false:
var x = "";
Boolean(x); // returns false
// The Boolean value of undefined is false:
var x;
Boolean(x); // returns false
// The Boolean value of null is false:
var x = null;
Boolean(x); // returns false
// The Boolean value of NaN is false:
var x = 10 / "H";
Boolean(x); // returns false
</script>
2. JavaScript Comparison and Logical Operators
1) Comparing Different Types
When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison.
An empty string converts to 0.
A non-numeric string converts to NaN which is always false.
Case | Value |
---|---|
2 < 12 | true |
2 < “12” | true |
2 < “John” | false |
2 > “John” | false |
2 == “John” | false |
“2” < “12” | false (alphabetically) |
“2” > “12” | true |
“2” == “12” | false |
2)JavaScript Bitwise Operators
Operator | Description | Example | Same as | Result | Decimal |
---|---|---|---|---|---|
& | AND | x = 5 & 1 | 0101 & 0001 | 0001 | 1 |
| | OR | x = 5 | 1 | 0101 | 0001 | 0101 | 5 |
~ | NOT | x = ~ 5 | ~0101 | 1010 | 10 |
^ | XOR | x = 5 ^ 1 | 0101 ^ 0001 | 0100 | 4 |
<< | Left shift | x = 5 << 1 | 0101 << 1 | 1010 | 10 |
>> | Right shift | x = 5 >> 1 | 0101 >> 1 | 0010 | 2 |