HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Readability of JavaScript shorthand for converting strings to numbers with default value

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
javascriptreadabilitynumberswithshorthandvaluedefaultforconvertingstrings

Problem

This is perfectly readable code to me, but I'm afraid it may be too confusing to others. What do you think?

Note that I'm not interested in validation of the input here (validation will happen long before we get to this line in the code), so assume it is blank or a valid non-negative integer.

It's modified from this Stack Overflow question.

var numberToAdd = parseInt($('#number-to-add').val()) || 500; // if a number is not provided, use 500

Solution

Seems fine syntactically and perfectly idomatic, but always, always supply a radix argument to parseInt:

var numberToAdd = parseInt($('#number-to-add').val(), 10) || 500;


To quote MDN:


radix: An integer that represents the radix of the [...] string. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior. Different implementations produce different results when a radix is not specified.

[...]

If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.

(emphasis in the original)

Code Snippets

var numberToAdd = parseInt($('#number-to-add').val(), 10) || 500;

Context

StackExchange Code Review Q#52102, answer score: 4

Revisions (0)

No revisions yet.