JavaScript Order of Operations

JavaScript Order of Operations | The adage “Please Excuse My Dear Aunt Sally” or PEMDAS may be known to you. It displays the operator precedence or order of operations in mathematical equations.

  • Parentheses
  • Exponents
  • Multiplication/Division
  • Addition/Subtraction

Although these laws are broadened in programming languages, they nonetheless have a similar structure. just omitting the well-known phrase.

You have used JavaScript’s operator precedence if you have ever declared a variable. The operator precedence table is included in the MDN documentation. This table is divided into sections, and the precedence of each operator is assigned a number. Understanding that the greater number is parsed first is crucial. Also see:- JavaScript Operator Precedence

Let us look at a few examples:

const a = 2 + 4 * 7;
console.log(a); 

Output:-

30

How many operators can you count in the aforementioned example? The assignment operator = is a third less evident operator in addition to the two obvious operators (+ & *).

This line of code’s flow of operations is rather simple to understand.

  • ‘a’ is a variable that has been declared.
  • “a” denotes a mathematical equation.
  • JS figures out the equation:
  • 4 * 7 is calculated. PEMDAS’s multiplication component, or the 15th power on the table,
  • 2 plus 28 occurs. PEMDAS addition component, often known as power 14,
  • The assignment operator, which has a precedence power of 3, resolves to assign our variable a value of 30.

When there are several operators with the same precedence, the associativity difference is relevant.

const b = (12 - 2) + 8 > 1 + 3;
console.log(b); 

Output:-

true

  • Parentheses come before anything else, 12-2.
  • The following two operations are addition and subtraction, in the associative sequence of left to right.
    • 10 + 8
    • 1 + 3
  • Our logical operator is now: 18 >4
  • b is finally given the value true. 18 is more than 4, thus 18.
  • The aforementioned examples are straightforward and don’t veer too far from mathematics. Operator precedence has many edge cases, many of which I’m sure I haven’t even encountered yet.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *