Mayur Buragohain Mayur Buragohain - 4 months ago 6x
Javascript Question

Arithmetic giving incorrect result

I need to evaluate the result of the following expression:

startCell = 50
size = 9
cnt = 1
var res = startCell + (size * cnt) + cnt

But if I alert
, I'm getting 591. What I should be getting is 60. I tried this:

var res = eval(startCell + (size * cnt) + cnt);

but it still gives me 591. Why is this happening?


There is nothing wrong with the code you posted. Proof:

The cause of your problem is in the code we can't see. Something is turning cnt into a string, but startCell and size are still numbers. If they were all strings, you'd get 5091 instead of 591:

It could be that cnt is being initialized to a string:

startCell = 50
size = 9
cnt = "1"

Or it could be initialized as a numeric value, but then transformed into a string by JavaScript's type coercion:

cnt = 1
cnt += ""

There are a lot of ways it could happen, and no one can know for sure without seeing the code. I suggest you look for every line that modifies cnt between the time you initialize it and the time you use it.

Also, be warned about eval. It's potentially dangerous when used incorrectly, and it's terrible for performance. You should avoid using eval when you can, at any skill level.