We'll discuss the three logical operators in JavaScript, which are detailed in the table below. These are the not (!
), and (&&
), and or (||
) operators. These are commonly used when working with Boolean values.
To better understand how these operators work, let's dive in to some exercises instead.
- Declare a variable called
isRed
and set its value totrue
. - Log to the console the result of
!isRed
.!
is the not operator. - Log to the console the result of
!!isRed
. Negating a negation just brings back the original value! - Declare a variable called
isRound
and set its value tofalse
. - Log to the console the result of
isRed && isRound
. Here we're trying to check if something is both red AND round. - Log to the console the result of
isRed || isRound
. In this example, we're trying to see if something is either color red or is round in shape (or both!). - Change the value of
isRound
totrue
and try doing exercises 5 & 6 again. What changed in the output? Does it make sense with the description of the logical operators? - Try logging to the console the result of
true && true && true
. This shows us we can keep extending theexpression
. You can even try outfalse || false || false || false
and keep going on and on... - Finally, try combining all three and use parentheses
()
to group statements together if it gets too complicated.!true && (false || true) && !false