let a = 2; let b = '3'; let c = a + b; console.log(a, c)
The output is going to be:
This means that the value of
a, which is an integer, was coerced into a string, then
3 were concatenated like two strings being added together rather than two integers being added together.
The value of
a remains an integer, but it was used as a string for the calculation. This will hold true even if you declare
const instead of
let because the value that’s coerced is a temporary copy, not the variable itself.
That said, you could redefine
a as a string containing “boo” in either language at some point before adding
'boo' 'boo3' as the result.
Type coercion is dangerous
One of the things that makes dynamically typed languages dangerous is the fact that you can’t always rely on
a = b; // assigns the value of b to a a == b; // will use type coercion to compare the two if possible a === b; // uses strict equality, both must be the same type and value
Those double equals can get tricky.
'1' == 1 // true '1' === 1 //false 0 == false // true 0 === false // false
But Python doesn’t coerce types
If you Google “does python coerce types,” the top answers will all say no. What does that mean?
'1' == 1 // False, because no coercion '1' + 1 // error because you can't add str and int types with the + operator
Python doesn’t have a triple equals out of the box because it doesn’t need it. As it doesn’t coerce types, it doesn’t need a special comparison mode that prevents coercion.
'1' == 1 is a
False statement in Python. Also worth noting that I use ‘False’ instead of ‘false’ for Python because it uses a capital letter at the beginning of its boolean values, which threw me the first time I encountered that.
I know, not earthshaking, but something that stood out to me enough to be worth writing about.