What values are truthy and falsy in JavaScript?
20 Apr 2019In most languges, conditional control statements often require expressions that
evaluate to boolean values: one of true
or false
. In JavaScript however,
non-boolean values can also be used in conditional control statements. Values
that are treated as false
but are not actually false
themselves are said
to be falsy
. The same goes with truthy
values with respect to true
.
Here’s a simple example, where we have a string
value being used in place
of a boolean.
const test = 'hello there'
if (test) {
console.log('This value is truthy') // <---- This will run
} else {
console.log('This value is falsy)
}
Since non-empty strings are considered truthy in JavaScript, the first console.log statement runs.
Use cases
There are a few common cases in which people tend to use non-boolean values as booleans.
Default values
Since null
and undefined
are falsy, they’re often used in conditional
statements to check if a variable has been assigned a value, and then assign
one if it hasn’t.
let test
if (!test) {
test = 'this is now assigned'
}
console.log(test) // => 'this is now assigned'
We can also rewrite this example to be a little more brief, like so:
let test
test = test || 'this is now assigned'
console.log(test) // => 'this is now assigned'
Non-zero number checking
0
is also falsy in JavaScript, so when dealing with numbers we can use if
statements and similar language constructs to both test if a number is 0.
Non-empty string checking
Since the empty string (''
) is considered falsy, we can easily use it in conditionals
when dealing with strings in our application logic. For example, imagine a file
that has been read into memory in an array and split by newline, with the
ending \n
stripped out. If we wanted to filter out empty lines, we could do:
const allLines = ['this is a line', '', 'another line', 'this is also a line']
const nonEmptyLines = allLines.filter(line => line)
console.log(nonEmptyLines) // => ['this is a line', 'another line', 'this is also a line']
Finally, here’s a handy reference of what JavaScript considers truthy and falsy.
List of truthy values
- All objects, including
{}
and[]
- Empty arrays
- Non-empty strings, including
' '
- All numbers, including negative ones
true
- functions
List of falsy values
''
0
null
undefined
NaN
false