To check if a value is truthy (it evaluates to true
) we can write it like this:
if (value) {
// Code will get executed if value is truthy
}
Falsy values
- An empty string (
""
, ''
)
- The boolean
false
null
undefined
- The number
0
NaN
Truthy values => Everything that is not falsy (1
, "Hello"
, true
, etc.)
Sometimes, we want to check if a value is falsy (evaluates to false
). To do this, we can use the NOT operator:
if (!value) {
// Code will get executed if value is falsy
}
Finally, we can check if a value is equal to a specific value. E.g. if a variable is equal to the numeric value 2
if (value === 2) {
// Code will get executed if value is equal to the numeric value 2
}
===
: The strict equality comparison operator will check if the value on the left-hand side is equal to the value on the right-hand side and if the value on the left-hand side is the same data type as the value on the right-hand side
==
: The abstract equality comparison operator will only check if the value on the left-hand side is equal to the value on the right-hand side. It will not check for equal data types meaning "2" == 2
evaluates to true