Search code examples
javascriptparseint

difference beween parseint and minus


Usually when I have to parse number in javascript I use code like

var x="99"
var  xnumber= x-0

instead of

var xnumber= parseInt(x)

Is there any problem in using this Code ( in the performance or the structure ) and I want to know if there is any problem


Solution

  • Using the "x - 0" method is going to be significantly faster in most browsers.

    Here's a JSPerf that shows the performance difference.

    You can do you own A/B performance testing using JSPerf.com

    However, you may still want to use parseInt() in some cases, because it's a little clearer. Although, truthfully, any experienced javascript developer isn't going to have any trouble understanding the faster way.

    If the line of code is only going to run once every half second or so (or whenever the user types a letter), you can use parseInt without worrying.

    However, if this bit of code is in a loop that runs a few thousand times or more, you should definitely use x - 0.