I Don't Know Javascript Coercion, Do You?

codenutt

Jared

Posted on November 24, 2019

I Don't Know Javascript Coercion, Do You?

I've made a grave mistake

In a video I published a few weeks ago, I made a rather basic mistake.

Given the following variables...

    let threeString = "3";
    let threeNum = 3;
Enter fullscreen mode Exit fullscreen mode

What does this expression evaluate to?

    threeString + threeNum
Enter fullscreen mode Exit fullscreen mode

If you're smarter than I was an hour ago, you'll know that it evaluates to "33".

Gordon Ramsay - Youre a string mate

Why does it do that?

According to ECMAScript, as summarized by Valentino:

If x is String or y is String then return ToString(x) followed by ToString(y)

In other words, if there is an expression with the + operator, and one of the values is a string, it will always coerce the values into a string.

Final Thoughts

I like to think I'm not completely dumb. I've been building websites/web apps in Javascript for about four years now. However, we all make mistakes. Even the most basic ones! Own up to them, and we'll all learn something. I know I did!

If you want to see my mistake in action, check out the video below!

And the follow up video, which I made before this mistake I made was pointed out...

πŸ’– πŸ’ͺ πŸ™… 🚩
codenutt
Jared

Posted on November 24, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related