javascript - parseInt vs unary plus - when to use which -


what differences between line:

var = parseint("1", 10); // === 1 

and line

var = +"1"; // === 1 

this jsperf test shows unary operator faster in current chrome version, assuming node.js!?

if try convert strings not numbers both return nan:

var b = parseint("test" 10); // b === nan var b = +"test"; // b === nan 

so when should prefer using parseint on unary plus (especially in node.js)???

edit: , what's difference double tilde operator ~~?

please see this answer more complete set of cases




well, here few differences know of:

  • an empty string "" evaluates 0, while parseint evaluates nan. imo, blank string should nan.

    +'' === 0;              //true isnan(parseint('',10)); //true 
  • the unary + acts more parsefloat since accepts decimals.

    parseint on other hand stops parsing when sees non-numerical character, period intended decimal point ..

    +'2.3' === 2.3;           //true parseint('2.3',10) === 2; //true 
  • parseint , parsefloat parses , builds string left right. if see invalid character, returns has been parsed (if any) number, , nan if none parsed number.

    the unary + on other hand return nan if entire string non-convertible number.

    parseint('2a',10) === 2; //true parsefloat('2a') === 2;  //true isnan(+'2a');            //true 
  • as seen in comment of @alex k., parseint , parsefloat parse character. means hex , exponent notations fail since x , e treated non-numerical components (at least on base10).

    the unary + convert them though.

    parseint('2e3',10) === 2;  //true. supposed 2000 +'2e3' === 2000;           //true. one's correct.  parseint("0xf", 10) === 0; //true. supposed 15 +'0xf' === 15;             //true. one's correct. 

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -