Booleans
A boolean value is either true
or false
.
The most common way you will encounter a boolean is when it is produced by comparison of two other values.
Comparing for equality
There are two operators for comparing whether two values are equal in JavaScript: ==
and ===
.
The double equal sign is the loose equality operator, which checks if two values are equal after converting them to a common type.
The triple equal (===
) is the strict equality operator, which checks that two values are equal and of the same type without performing
any type conversions. If the values are different types, the comparison will return false
.
Comparing for inequality
The inverse to strict/loose equality is strict and loose inequality - !=
and !==
.
And operator
In the example below, the and operator (&&
) produces true
if both values are true
.
Unlike other programming languages, TypeScript allows you to use the &&
operator with any values, not just booleans. If both values are equivalent to true
, the value on the right is produced by the expression.
Certain values in JavaScript are equivalent to false
, like the number 0
or the empty string ""
(a string with no characters). These values are often referred to as falsy, while all other values are referred to as truthy. Try modifying the program below to discover which values are truthy and which ones are falsy.
Or operator
In the example below, the or operator (||
) produces true
if either boolean is true
.
Not operator
Ternary operator
A ternary expression produces one of two values based on whether a boolean is true
or false
.
If the boolean value is true
, the value left of the colon (:
) is produced. If the value is false
, the value right of the
colon is the result of the ternary expression.
A common programming pattern in JavaScript is to use boolean operators when conditionally operating on values.
A boolean value is produced by comparison operators like <
(less than) and >
(greater than).