Wednesday 10 October 2012

Javascript Jinx: Parsing 'Infinity' to get a number

Everyone would agree Javascript is an insane language. It is very easy to make a mistake in Javascript.One thing about Javascript that makes it harder to code in it is that it is a very forgiving language. It does not raise errors (except in extreme cases). So, there are high chances of the code behaving weirdly.

Here is one awesome trick in Javascript. We know that in Javascript, there is no divide-by-zero error. Instead, when you try to divide any number by zero, you get a special number called Infinity. And this trick is about parsing Infinity to get a number.

Try to run this code in Javascript:
var result = parseInt(1/0, 19);
console.log(result);
The result is most unexpected. The output would be: 18.

Wondering how? This is what happened:

1. 1/0 gave Infinity
2. The base here is 19, so Javascript tried to convert ‘Infinity’ to a number in base 19
3. In base 19, the letter I corresponds to digit 18 (like F to 15 in hexadecimal)
4. So, it converted I to 18, then ignored rest of the string since n is not a valid string, and thus we reached 18.

Amazing isn’t it? This is why we have to be very careful with Javascript. Another version of the same trick:
var result = parseInt(1/0, 24);
console.log(result);
This time, the base was 24. So, this string is parsed: Infini, its parsed upto t since is it not a valid number in base 24, and then Infini is converted to a number to get 151176378 as the output.

(Courtersy: Stack Overflow)
P.S: This trick is so famous, try to search 'parseInt(1’ in Google, you will get an instant result.

No comments:

Post a Comment