Operator precedence

·

2 min read

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;
  1. Variable b is assigned as 1.

  2. Variable a is assigned as b = 1.

  3. b = 1 returns the value 1, so variable a is now assigned as 1.

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;
  1. We resolve the document variable to be the document object.

  2. We use dot notation to retrieve the getElementById function. (The function is a property of the document object).

  3. We attempt to call it, but before the call can proceed we must first evaluate the function's arguments.

  4. We resolve the id variable to be the string "header".

  5. The getELementById function returns an HTMLElement object and then uses dot notation to access value.

  6. 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;
  1. number3 is resolved to its value.

  2. The function is invoked, but its variables need to be resolved.

  3. number1 and number2 are resolved to their values.

  4. The function is invoked so number1, number2, and number3 are finally added together!