A boolean is a two-state value representing either truth or falsehood (in JavaScript, true
or false
). When values of other types are coerced to boolean, they are said to be either truthy or falsy. A variety of operators are available for working with (explicit or implicit) booleans.
References | ECMA | Mozilla | Microsoft |
---|---|---|---|
Literals | [1] | [2] | [3] |
Objects | [4] | [5][6] | [7] |
Operators[]
Comparison operators[]
Comparison operators are operators that take two values of any type and return a boolean value. Objects are compared by identity. NaN returns false in any sort of comparison.
== (Type-Coercing Equals)[]
Check the two operands for equality. If the values are of different types, they will be coerced to the appropriate types rather than being considered automatically unequal. Beware: can have some unintended effects. Unless you've thought the possibilities through carefully, use ===
.
2 + 2 == 4 // true
2 + 2 == "4" // true
1 == true // true
2 + 2 == 5 // false
!= (Type-Coercing Not Equals)[]
The type-coercing equivalent to !==
. a != b
is equivalent to !(a == b)
.
2 + 2 != 5 // true
2 + 2 != 4 // false
2 + 2 != "4" // false
Combination operators[]
These operators take two boolean values and return one of their operands. They are short-circuit: if the result of the expression can be determined from the first operand, the second operand will never be evaluated.
&& (Logical And)[]
Returns the first falsy operand, or the second operand if both are truthy. Also known as 'guard', since its short-circuit behaviour can be used to stop an expression's execution if a value is falsy.
true && true // true
true && false // false
true && "" // ""
"" && true // ""
"a" && "" // "a"
"a" && 5 // 5
true && 4 // 4
false && 4 // false
|| (Logical Or)[]
Returns the first truthy operand, or the second operand if both are falsy. Also known as 'default', since its short-circuit behaviour can be used to provide a default replacement if a value is falsy.
true || true // true
true || false // true
false || "bar" // "bar"
"foo" || "bar" // "foo"
"" || "bar" // "bar"
Transformation operators[]
! (Not)[]
Finds an expression's logical inverse. Note: two of these in a row will convert a value to its boolean opposite and then the boolean opposite of that, effectively converting a value to a boolean.
!true // false
!false // true