Table of contents
One of the lesser-known concepts in both Python and JavaScript is truthy and falsy values. This means that, in both languages, there is a certain set of values that evaluate to FALSE and the remaining values evaluate to TRUE.
Python
Falsy values are:
None
False
Numbers equal to zero:
0
,0.0
,0j
Empty sequences and collections. Common ones are:
[]
,()
,''
,range(0)
,set()
,{}
, emptybytearray
, emptymemoryview
Any object for which
obj.__bool__()
returns False. Orobj.__len__()
returns 0 ifobj.__bool__
is undefined.
if []:
print("Empty list is True")
else:
print("Empty list is False")
# Output: Empty list is False
All remaining values evaluate to true
. This means that the following code prints true:
print(bool("[]")) # Output: True
JavaScript
Falsy values are null
, undefined
, NaN
, ''
, 0
, false
As you can see, the number of falsy values is more in Python as compared to JavaScript.
if ('') {
console.log('Empty string is true')
}
else {
console.log('Empty string is false')
}
// Output: Empty string is false
All remaining values evaluate to true
. This means that the following code prints true:
console.log(Boolean("undefined")) // Output: true
Code example
You can use this concept to shorten the code you write. For example, let's say you want to find all nonempty strings in a list of strings that you got from a database
let names = ["Aaron", "James", "", "Julie", null, "Jane"]
console.log(names.filter(name => name).join(','));
names = ["Aaron", "James", "", "Julie", None, "Jane"]
print(','.join(name for name in names if name))
Output in both cases: Aaron, James, Julie, Jane
Summary
We saw the values which are falsy in both JS and Python and also one of their application in code. Let's summarize all the falsy values in a table:
Language | Falsy Values |
JavaScript | null, undefined, NaN, '', 0, false |
Python | None, False, Numeric zeroes, Empty sequences and collections, objects for which __bool__ returns False or __len__ returns 0 if __bool__ is undefined |