This small blog was sparked by a post that I saw:
There are many posts like the above on the internet, and almost all of them are because of this type coercion thingy. So in this blog, I’m gonna try to explain what type coercion is and what’s happening in that post 😉.
What is type coercion?
Some fun examples:
"a" + 0 = "a0"-> Number coerced into a string.
- true + 0 = 1 -> Boolean coerced into a Number.
- true + 2 = 3 -> True coerced into the number one(1).
- false + 2 = 2 -> False coerced into the number zero(0).
- +true = 1 -> Our `
+` here is a unary operator which is trying to coerce a boolean into a Number.
So what’s happening in our expression
('b' + 'a' + + 'a' + 'a').toLowerCase() is:
The first two characters are simply concatenated, then
+'a' coerces a character into a Number, which results in a NaN because
NaN is of data type Number as well,
NaN gets coerced into a string because it’s being added to
Thank you for reading the post!