Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

You probably know our good old friend parseInt and its quirks.

// it ignores whitespace
parseInt("   123 "); // 123

// it ignores leading zeros
parseInt("077"); // 77

// it truncates the decimal part
parseInt("1.9"); // 1

// it parses numbers sometimes with a different base
parseInt(015); // 13
parseInt('0x14'); // 20

I've just read Aleksandr's post and learned about a parseInt superpower.

Apparently, parseInt can parse Emoji numbers correctly!

parseInt('1️⃣'); // 1
parseInt('2️⃣'); // 2
parseInt('3️⃣'); // 3

What? It doesn't make any sense that this works!

And, of course, parseInt can't parse Emoji numbers, but the combination of how Emoji numbers are put together and a parseInt quirk makes it appear as if parseInt could parse Emojis.

I always thought parseInt would try to parse the entire passed-in value, and if it failed, it would return NaN. And this is mostly correct...

parseInt('wat');     // NaN
parseInt('wat', 10); // NaN

... unless the value you want to parse starts with a numeric value like the number Emojis (1️⃣ = 1 + more code points).

parseInt('1w');     // 1
parseInt('1w', 10); // 1

parseInt('1.5w');     // 1
parseInt('1.5w', 10); // 1

If your value starts with an unparsable character, you'll be back at NaN.

parseInt('a1w');     // NaN
parseInt('a1w', 10); // NaN

I must say I find this wild and confusing, but I guess this behavior was put in there to parse numbers with units more easily.

parseInt('12€'); // 12

However, JavaScript never holds back with a twist. Philipp pointed out that the Number() constructor behaves differently.

Number('1️⃣');   // NaN
Number('1w');   // NaN
Number('1.5w'); // NaN
Number('a1w');  // NaN
Number('12€')   // NaN

Number('1.2'); // 1.2

Well, it's good to know about all these quirks!

If you enjoyed this article...

Join 5.7k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles