Exponentiation operator precedence

Ethan Resnick ethan.resnick at gmail.com
Thu Aug 27 18:20:38 UTC 2015

Long-time esdiscuss lurker; hopefully this perspective is helpful.

I think the problem here is that traditional mathematic notation uses
visual cues to imply precedence that JS can't take advantage of. When -3 **
2 is written out on paper, the 2 is very clearly grouped visually with the
3. In fact, the superscript almost makes the 2 feel like an appendage of
the 3. That makes it more natural to read it as two items: the negative
sign, and (3 ** 2).

By contrast, when (-3 ** 2) is written out in code, the negative sign is
way closer visually to the 3 than the 2 is, so I find myself
instinctively pulling out a "-3" first and reading the expression as

Treating -3 ** 2 as -(3 ** 2) seems technologically possible and
mathematically sensible, but also like it's going against the grain of the
human visual system. I think that's at least one reason to value the
"binary precedence should be
lower than unary" principle.

The `Number.prototype.pow` approach might be an improvement, as it has the
effect of mandating parentheses on some cases that might otherwise be
confusing (e.g. x ** y ** z)  and it offers most of the conciseness of
**. But -x.pow(2) still feels unpredictable to me as an everyday programmer
switching between languages. (Also, pow() requires an extra set of
parentheses if I want to operate on a literal.)

Maybe it's ok if the operator surprises some people in some cases, and the
guidance will just become to use parentheses if you're unsure. That
occasional uncertainty for the vast majority of JS programmers that aren't
doing much exponentiation might be worth it if ** makes a minority of JS
programmers much more productive. I don't know.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20150827/fb0ba748/attachment.html>

More information about the es-discuss mailing list