February 10, 2007

Tricky alternatives to toString() and parseInt()

JavaScript is Loosely typed

JavaScript is dynamically typed, making things extremely flexible. Suppose you have a text field for inputting birth year and want to greet to people born after 1984, simply write

var birthYear = document.getElementById('txtBirthYear').value;
if (birthYear > 1984) {

When JavaScript sees you compare a String with a Number, it automatically converts the String to Number and the perform comparison.

But sometimes the ambiguity of type causes problems. 1 + '1' evaluates to '11' instead of 2. This may cause hard to find bugs. Douglas Crockford categorizes "the overloading of + to mean both addition and concatenation with type coercion" as a design error of JavaScript in his famous article on The World's Most Misunderstood Programming Language.

Still we often need to convert data type between String and Number. To convert variable i to String, simply call i.toString(). To convert s to a Number, we use Number(s). This is nice and clear.

The empty string ('') concatenation trick, the plus sign (+) trick and the minus zero (- 0) trick

But for guys who want to squeeze every byte. There are tricky alternatives.

  • To convert x to String: x + ''
  • To convert x to Number: +x
  • To convert x to Number: x - 0

For examples,

1 + 2 + 3 //produces 6
'1' + 2 + 3 //produces '123'
'1' - 0 + 2 + 3 //produces 6
'1' + '2' //produces '12'
+'1' + +'2' //produces 3

Notice that +x and x-0 doesn't mean parseInt(x) or parseFloat(x), it doesn't do any further parsing.

parseInt('2007 is promising') //produces 2007
+'2007 is promising' //produces NaN
Let's call them the empty string concatenation conversion trick, the plus sign and the minus zero trick. Both of the tricks sacrifice clarity and make code harder to understand.


Chris said...

You seem to have a small error in your article:

+'1' + +'2' //produces 12

I am sure you meant to write

+'1' + +'2' //produces 3

At least thats what I am getting.


Arrix said...

Ah, yes! Thanks for pointing out.

Anonymous said...

Online Casinos Free tyuueooru
Online Casinos
Last but not least, prior to participating in any of the online casino websites no matter it's freely accessible or it requires a certain amount of money to get started with, make sure that you have gone through their ?Terms and Conditions? in a thorough manner.
[url=http://www.nhgaa.org/]Free Games Casino[/url]
For this purpose, you may require checking out the lists of good gambling websites that are offered on various sites in the form of ratings, reviews, etc.
http://www.nhgaa.org/ - No Download Casino
If you end up choosing a not-so-good online casino website, you'll never enjoy the actual pleasure arriving with online gambling.