Parseint VS Unary Plus, When to Use Which

parseInt vs unary plus, when to use which?

Well, here are a few differences I know of:

  • An empty string "" evaluates to a 0, while parseInt evaluates it to NaN. IMO, a blank string should be a NaN.

      +'' === 0;              //true
    isNaN(parseInt('',10)); //true
  • The unary + acts more like parseFloat since it also accepts decimals.

    parseInt on the other hand stops parsing when it sees a non-numerical character, like the period that is intended to be a decimal point ..

      +'2.3' === 2.3;           //true
    parseInt('2.3',10) === 2; //true
  • parseInt and parseFloat parses and builds the string left to right. If they see an invalid character, it returns what has been parsed (if any) as a number, and NaN if none was parsed as a number.

    The unary + on the other hand will return NaN if the entire string is non-convertible to a number.

      parseInt('2a',10) === 2; //true
    parseFloat('2a') === 2; //true
    isNaN(+'2a'); //true
  • As seen in the comment of @Alex K., parseInt and parseFloat will parse by character. This means hex and exponent notations will fail since the x and e are treated as non-numerical components (at least on base10).

    The unary + will convert them properly though.

      parseInt('2e3',10) === 2;  //true. This is supposed to be 2000
    +'2e3' === 2000; //true. This one's correct.

    parseInt("0xf", 10) === 0; //true. This is supposed to be 15
    +'0xf' === 15; //true. This one's correct.

Is there any reason not to use the plus operator instead of Number() or parseInt() to return a number?

As far as I know the first two are completely equivalent, and the choice between them is a matter of taste. (Personally I prefer the unary + because it's more concise, and well understood by most JS developers.)

parseInt is different because it reads a number value from the start of the string and ignores the rest when it reaches a non-numeric character. A common use is getting the underlying number from a CSS value like "20px". Note that the other two methods would fail with a NaN in this case.

What is the difference between Unary Plus/Number(x) and parseFloat(x)?

The difference between parseFloat and Number

parseFloat/parseInt is for parsing a string, while Number/+ is for coercing a value to a number. They behave differently. But first let's look at where they behave the same:

parseFloat('3'); // => 3
Number('3'); // => 3
parseFloat('1.501'); // => 1.501
Number('1.501'); // => 1.501
parseFloat('1e10'); // => 10000000000
Number('1e10'); // => 10000000000

So as long as you have standard numeric input, there's no difference. However, if your input starts with a number and then contains other characters, parseFloat truncates the number out of the string, while Number gives NaN (not a number):

parseFloat('1x'); // => 1
Number('1x'); // => NaN

In addition, Number understands hexadecimal input while parseFloat does not:

parseFloat('0x10'); // => 0
Number('0x10'); // => 16

But Number acts weird with empty strings or strings containing only white space:

parseFloat(''); // => NaN
Number(''); // => 0
parseFloat(' \r\n\t'); // => NaN
Number(' \r\n\t'); // => 0

On the whole, I find Number to be more reasonable, so I almost always use Number personally (and you'll find that a lot of the internal JavaScript functions use Number as well). If someone types '1x' I prefer to show an error rather than treat it as if they had typed '1'. The only time I really make an exception is when I am converting a style to a number, in which case parseFloat is helpful because styles come in a form like '3px', in which case I want to drop the 'px' part and just get the 3, so I find parseFloat helpful here. But really which one you choose is up to you and which forms of input you want to accept.

Note that using the unary + operator is exactly the same as using Number as a function:

Number('0x10'); // => 16
+'0x10'; // => 16
Number('10x'); // => NaN
+'10x'; // => NaN
Number('40'); // => 40
+'40'; // => 40

So I usually just use + for short. As long as you know what it does, I find it easy to read.

What is the difference between parseInt() and Number()?

Well, they are semantically different, the Number constructor called as a function performs type conversion and parseInt performs parsing, e.g.:

// parsing:
parseInt("20px"); // 20
parseInt("10100", 2); // 20
parseInt("2e1"); // 2

// type conversion
Number("20px"); // NaN
Number("2e1"); // 20, exponential notation

Also parseInt will ignore trailing characters that don't correspond with any digit of the currently used base.

The Number constructor doesn't detect implicit octals, but can detect the explicit octal notation:

Number("010");         // 10
Number("0o10") // 8, explicit octal

parseInt("010"); // 8, implicit octal
parseInt("010", 10); // 10, decimal radix used

And it can handle numbers in hexadecimal notation, just like parseInt:

Number("0xF");   // 15
parseInt("0xF"); //15

In addition, a widely used construct to perform Numeric type conversion, is the Unary + Operator (p. 72), it is equivalent to using the Number constructor as a function:

+"2e1";   // 20
+"0xF"; // 15
+"010"; // 10

What is the difference between a *= 1 and a = +a?

There isn't any difference. They are both converted to numbers using a ToNumber conversion. And the numerical multiplication by 1 and unary plus operation keep the values the same.

What does = +_ mean in JavaScript

r = +_;
  • + tries to cast whatever _ is to a number.
  • _ is only a variable name (not an operator), it could be a, foo etc.

Example:

+"1"

cast "1" to pure number 1.

var _ = "1";
var r = +_;

r is now 1, not "1".

Moreover, according to the MDN page on Arithmetic Operators:

The unary plus operator precedes its operand and evaluates to its
operand but attempts to converts it into a number, if it isn't
already
. [...] It can convert string representations of integers and
floats, as well as the non-string values true, false, and null.
Integers in both decimal and hexadecimal ("0x"-prefixed) formats are
supported. Negative numbers are supported (though not for hex). If it
cannot parse a particular value, it will evaluate to NaN.

It is also noted that

unary plus is the fastest and preferred way of converting something into a number



Related Topics



Leave a reply



Submit