DEV Community

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

Collapse
 
codingknite profile image
Joel P. Mugalu

Hey...I appreciate your comment.

Regarding operator precedence, I'm not sure I understand what you're trying to say. Perhaps it's how I explained it.
The following is the definition of operator precedence according to Wikipedia

"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"

And that Is what I meant...operators with higher precedence are evaluated before operators with a lower precednce. Hence the multiplication happens before addition...because (*) has a higher precedence than (+).

As for the ternary operator...its called the conditional (ternary) operator. I don't think it makes any sense to be dogmatic about it. I think what matters is understanding what it does rather than being religious about what its called.

For undefined, unset value is actually easier a definition. So I'm going to in cooperate that. Otherwise thanks for your views.

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'? :)