16.6.16

What The JS?



I just stumbled upon a JS issue concerning the precedence of arithmetic operations.

To reproduce this issue type in the following expression in the Javascript console:

((((601298881-1)/2)+1)*(((601298881-1)/2)+1))

And then type the same expression into a scientific calculator.

You'd expect the same answer because it is the same expression. 

Below is a screenshot of the heartbreaking truth. 





I had to ask one other person to confirm this before writing this blog post. This can also be reproduced by removing the outermost brackets from the above expression.

According to specifications, the grouping ( ) operator should control the precedence of operations.

The function below returns the same wrong result when n = 601298881, perhaps it is hitting some limit somewhere?

//this function requires an even n or else it returns 0
function squaring_impossible(n)
{
 parseInt(n);
 if(n%2!=0){return 0;}
var halfish = ((n-1)/2)+1;
var square = halfish*halfish;
return square;
}

This is in all major browsers across different operating systems.

Update: Turns out the maximum int that Javascript can handle properly is
9007199254740991