JS :: Summing numbers over a range of lines (with Array.reduce)

PS another balance is, of course, between:

  • economy of ink (brevity of expressions)
  • economy of scripter time ( less puzzled time later, tracking down a bug )

In that light, my preference is to waste less debugging time, and be more relaxed about using more ink.

For example:

Bracketing ternary expressions

Where you have the perfectly clear and functional

sum += m ? (60 * parseInt(m[1], 10)) + parseInt(m[2], 10) : 0

I would tend to add parentheses, just because I have often found bugs that turned on what was (or wasn’t) included in the initial test section, for example.

sum += (m ? (60 * parseInt(m[1], 10)) + parseInt(m[2], 10) : 0)

Explicit or implied coercion

The advantage of implied coercion is that we have to type less. For example your implied coercion of a Regex match (null | Array) to a Bool:

m ?

Or the common coercion of numbers to strings.

Making coercions explicit, eg

Boolean(m) ? 

or

intMins.toString()

Is technically redundant in many contexts, does waste ink, and looks more noisy, but it’s also a way of reducing time looking for bugs later on.

Undetected automatic type-coercions are quite a productive source of unexpected JS bugs. : -)

That’s why for example, I prefer to never use the slower == (equality test after automatic type conversion) and always use the faster === (direct equality test, without type conversion)

2 Likes