Friday, 16 December 2022

Boolean Coercion/Conversion, JavaScript vs Python

How a not boolean value is mapped to true or false (either converted using a function or operator, or coerced when used in a boolean context) is one of those things that I need to rethink from time to time. Adding to this that my 2 main languages as of today, Python and JavaScript, have some differences on this topic, I've thought it useful to put a small summary here.

Javascript
This post is a pretty good reference. Falsy values in JavaScript are:
undefined and null (the 2 nullish values), false, NaN, 0 and "" (empty string).
We can convert any value to boolean either with '!!value' or with 'Boolean(value)'

There's something more to bear in mind. Not al falsy values have the same behaviour with the == operator. 0 is equal to false, and "" is equal to false:

0 == false
true
"" == false
true
1 == true
true

undefined == false
false
null == false
false
NaN == false
false

null == undefined
true

Python
Answers here are a pretty good reference. The following values are considered false:
None, False, 0, "" (empty string), any other empty container: (), [] and any empty mapping, for example, {}..
Additionally, a custom class can define the __bool__() method, that will be used when converting instances of that class to boolean.
We can convert any value to boolean either with 'not not value' or with 'bool(value)'

We also have to bear in mind what happens when using the equality operator "==". Only 0 == False and 1 == True are true. All other cases are false:

>>> 1==True
True
>>> 0==False
True
>>> None==False
False
>>> [] == False
False
>>> [] == True
False
>>> 2==False
False
>>> 2==True
False

So the big difference betwewn Javascript and Python regarding boolean conversion/coercion is that in JavaScript an empty array and an empty object are coerced to true, while in Python they are coerced to False. In addition, in Python we can customize the behaviour of our classes by implementing the __bool__ method.

No comments:

Post a Comment