Friday, November 16, 2012

Why do strings sometimes get changed to numbers in javascript?

I have this code:



function getSessionGUID() {
return (S4()+S4());
}

function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}


It clearly returns a string, but if you run it a bunch of times, you can notice that it sometimes returns infinity.



for (var i = 0; i < 100000; i++){ if(getSessionGUID() == Infinity) console.log(\"INFINITY\"); }
871 x INFINITY


I then noticed that if you remove the |0, it solves the problem:



function S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}


Results:



for (var i = 0; i < 100000; i++){ if(getSessionGUID() == Infinity) console.log(\"INFINITY\"); }
undefined


Why does this happen? In both cases the value is changed into a string.






Rating: 1 out of 5 based on 5 ratings



The post Why do strings sometimes get changed to numbers in javascript? appeared first on Javascript ASK.






via Javascript ASK http://javascriptask.phpfogapp.com/why-do-strings-sometimes-get-changed-to-numbers-in-javascript.html

No comments:

Post a Comment