Operator precedence
Just like with math and logical operators, the concepts of operator precedence also pertain to objects. Associativity determines the order of operation, along with precedence. There are two types of associativity: right-associativity and left-associativity.
Right-associativity is when code is evaluated right-to-left. Let's take a closer look at what is happening in the line of code below:
a = b = 1;
Variable
b
is assigned as1
.Variable
a
is assigned asb = 1
.b = 1
returns the value1
, so variablea
is now assigned as1
.
The assignment of variables takes lowest precedence, which is why we evaluate the return value of b = 1
before completing the assignment of variable a
.
The example below is left-associativity is when code is evaluated left-to-right. It evaluates the document.getElementById
method before accessing value
.
let id = "header";
let element = document.getElementById(id).value;
We resolve the
document
variable to be the document object.We use dot notation to retrieve the
getElementById
function. (The function is a property of the document object).We attempt to call it, but before the call can proceed we must first evaluate the function's arguments.
We resolve the
id
variable to be the string"header"
.The
getELementById
function returns an HTMLElement object and then uses dot notation to accessvalue
.Finally we do assignment which is the LOWEST precedence (that's why assignment happens last). Its associativity is right to left, so we take the value on the right and assign it to the left.
Now let's dive into the example below. Resolving the variables to their values happens before the operators.
add(number1, number2) + number3;
number3
is resolved to its value.The function is invoked, but its variables need to be resolved.
number1
andnumber2
are resolved to their values.The function is invoked so
number1
,number2
, andnumber3
are finally added together!