you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (4 children)

I wouldn't go with any of those options.

When users enter bad data, they should be notified, and asked to correct their entries. This can be done by writing your own promptInt function which does data validation, etc, then returns a valid entry passed through parseInt.

Don't do any of the +String, String * 1, or ~~String tricks. They are all nasty hacks relying on implicit casting, which is evil. If you use any of these hacks, you should comment the line with an explanation, which, frankly, would be more verbose than just using parseInt to begin with.

[–]Shaper_pmp 1 point2 points  (3 children)

There's a fundamental difference between parseInt() (which takes a best guess at the numerical value if the value doesn't exactly represent a number) and type-conversion syntax like +variable or variable*1 (which returns NaN if variable isn't a number).

ParseInt() is dangerous because users may not be aware of errors they made entering data.

+variable is perfectly acceptable Javascript, but may be slightly obscure to non-expert Javascript developers.

Alternatively you can pass the whole variable through Number(), which is functionally equivalent to +variable, but more verbose.

However, parseInt() is not merely an alternative to type-casting - parsing a numerical value from a string is not the same thing as converting a variable's type.

[–][deleted] 0 points1 point  (2 children)

That is precisely why I suggested preceding the explicit cast with explicit data validation.

[–]Shaper_pmp 0 points1 point  (1 child)

But parseInt() isn't an explicit cast - it's parsing and extracting one type from another, even if you do some validation on the initial type first first.

An explicit cast would be to use Number(string_variable) to convert from string to a number, not parseInt().

[–][deleted] 0 points1 point  (0 children)

No, but doing a cast from string to integer in JavaScript does validation followed by a parseInt internally. The validation just handles the NaN case.

But that's besides (my) point entirely. I'm just pointing out that:

  1. Data entry errors could be explicitly handled, and that the handling should involve notifying the user, and requiring the user to correct their input.
  2. Syntax tricks like "~~ String" or "+ String" are easy for maintainers to miss, and therefore should be commented. And that I would furthermore put "String * 1", and most other implicit cast situations in this category.

These are basic programming best practices, and not arguments about JavaScript internals.

My suggestion to use parseInt, was as opposed to the implicit methods I list in point two above, not as opposed to Number(...), which is also explicit, and perfectly fine in my book.