Operators
- A special function that is syntactically (written) differently
- Generally Operators take two parameters and return one results
var a = 3 + 4;
console.log(a);
How did the Javascript Engine do that?
They Syntax Parser saw the operator (+), actually a function like this:
function + (a, b) {
return
}
Called infix operation : Operation sits in between 3 + 4 instead of + 3 4 (prefix) , 3 4 + (postfix)
Operator Precedence and Associativity
Operator Precedence:
- Which operator function gets called first
- Functions are called in order of Precedence (Higher precedence wins)
Example:
var a = 3 + 4 * 5
console.log(a);
Starts with operator precedence:
14
Multiplication left‐to‐right
...*...
Division left‐to‐right
.../...
13
Remainder left‐to‐right
...%...
Addition left‐to‐right
...+...
Subtraction left‐to‐right
...‐...
On Chrome Dev Console:
> 23
Associativity:
- What order operator function get called in: Left-to-right or right-to-left
- When functions have the same precedence
Example:
var a = 2, b = 3, c = 4;
a = b = c
console.log(a);
console.log(b);
console.log(c);
On Chrome Dev Console:
> 4
> 4
> 4
Reasone: Due to Associativity of the assignment operator (right-to-left)
- So it go the furthest one to the right (c), because it is from right to left