4

Basically, I'm trying to figure out what the difference is between these 3 statements? Is there any reason to use one instead of the others? Is the first one bad practice (it works but I never see it and doesn't seem to be taught anywhere)?

+'21';
Number('21');
parseInt('21');
iPzard
  • 2,018
  • 2
  • 14
  • 24
  • Best answer in the duplicate links: https://stackoverflow.com/a/17106702/9867451 – ibrahim mahrir Sep 23 '18 at 16:42
  • 1
    The first one is only bad practice when it comes to readability. If there is a lot of noise around what you're converting, it could be easy to miss, while `Number` stands out. But if you have something like `return +result` that should be fine. A unary plus is idiomatic but I personally prefer `Number` for conversions because it's easier to see and you can also use it in something like `["1", "2", "3"].map(Number)` – VLAZ Sep 23 '18 at 16:49

2 Answers2

5

parseInt parses the string up to the first non-digit number and returns what it found,

For example: parseInt('123abc') // returns 123;

Number tries to convert the entire string into a number if it can.

ForExample: Number('123abc') // returns NaN

Unary plus operator can also be used to convert a string into a number, but it is not very readable when it is being used with other expressions and operators

Internally, +'21' will work in the same way as Number('21') * 1

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
3

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.

Robin Zigmond
  • 17,805
  • 2
  • 23
  • 34