6

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');
2
  • Best answer in the duplicate links: stackoverflow.com/a/17106702/9867451 Commented Sep 23, 2018 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) Commented Sep 23, 2018 at 16:49

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.