Javascript type conversion

Tags: programming, webdevelopment.
By lucb1e on 2012-07-14 02:59:07 +0100

I used to have a lot of problems with Javascript on this back when I was just starting to program and had no experience coding besides writing HTML. Nowadays I don't have any trouble with this anymore, especially since the discovery that you can see the errors, but only now I think I can guess right 100% of the time.

Let's do a show-by-example, but try to guess for before clicking the button!

var n = 1;
var leet = "1337";
var text = "text";

> n + n


> text + n  // Rule: If it can convert the types to make it work, it will.


> text - n  // It can't substract a number from a string


> leet + n  // Here it gets tricky: both vars can be converted to number and string, so which does it choose?


Rule: Converting to string precedes converting to number. Also n+leet would be converted to a string.

> leet * n  // string+num became string and you can't multiply a string, so NaN


But no, the "if it can convert" rules here. It converts to a number, so if we combine the previous two...

> leet * n + n  // ... it will suddenly treat it as a number.


> parseInt(leet) + 1  // Conclusion: to do string+number as calculation, we'll need to convert ourselves


One example of what I tried to do when just starting with programming Javascript was something like this:
> (prompt("number?", "30") + 10) / 25

Of course this gave a ridiculous number, 120.4 instead of 1.6 when using the default value of the prompt. It took a while to figure out that it doesn't see the number I gave as a number, especially since it worked other times with different arithmetic.

By the way, here is a short talk which is (partially) about Javascript's typing inconsistencies:
https://www.destroyallsoftware.com/talks/wat
It starts off with Ruby, but I think it's worth it to watch anyway ;)
lucb1e.com
Tip others about this page:   Share via Facebook  Share via Twitter  Share via Google+  Submit to Reddit  Recommend at StumbleUpon  Share by e-mail Submit at Hacker News


Comments:
Comments powered by Disqus
Another post tagged 'programming': 10 things Paul Irish learned from the jQuery source

Look for more posts tagged programming or webdevelopment.

Previous post - Next post