Assuming I have a numerical string:
var foo = "0";
Assume I want to parse it as a number, and increment it assigning the value to bar (just an arithmetical example), I know I could do:
var bar = parseInt(foo, 10)+1;
But I believe the above example could be simpler and more readable. Consider this example:
//alternative 1
var bar = +foo+1;
And this one:
//alternative 2
var bar = ++foo;
Both of these will also yield the same result for bar (the latter will also increment foo, but that’s no problem).
My question is, by using one of these alternatives, would I be exposing my code to the same possible implementation-dependant flaws of using parseInt without specifying a radix/base?
Or are these safe to use as well?
From the perspective of readability and maintainability
parseIntis the best choice. It clearly tells what it does and does it reliably.Tomorrow, when a fellow developer joins the project, of after a couple of months when you yourself will be looking at your own code, or if you suddenly decide to increment by ten instead of just one, you’ll be in less trouble working with
parseInt.Also, try JSLint. It’s worth it.