Fandom

JavaScript Wiki

Boolean

87pages on
this wiki
Add New Page
Talk4 Share

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]


OperatorsEdit

Comparison operatorsEdit

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)Edit

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)Edit

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 operatorsEdit

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)Edit

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)Edit

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 operatorsEdit

! (Not)Edit

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

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.