DEV Community

Discussion on: Data Types and Operators in JavaScript: Everything You Need To Know

Collapse
 
pentacular profile image
pentacular

"In mathematics and computer programming, the order of operations is a collection of rules that reflect conventions about which procedures to perform first in order to evaluate a given mathematical expression"

Yeah, I can see where this is coming from, but it's fundamentally incorrect.

You can think of predecence as showing where parentheses should be inserted to make the association of operand to operator clear.

e.g., a + b * c + d might become a + ((b * c) + d).

But this doesn't actually tell us what order the evaluation occurs in, and the system is free to rearrange things providing that these constraints are met.

For example, the system may understand that since x + y + z is equivalent to x + z + y, it can turn a + ((b * c) + d) into (a + b) + (b * c).

And, of course, it is free to evaluate a, b, c, and d in any order it likes, since there are no topological dependencies between those operations.

In javascript, evaluation is specified as being left-to-right, which means that if you run

const p = (v) => (console.log(v), v);
p(1) + (p(2) * p(3)) + p(4);
// You'll get 1, 2, 3, 4 output.

I really wish they'd stop calling operator associativity 'order of operations' because it's (a) wrong, and (b) misleads people into thinking of mathematics as a mechanical process, rather than being about relationships. :)

As to the 'ternary operator' ...

If the only binary operator were +, would you start calling it 'the binary operator'? :)