How Operator Precedence Works in JavaScript

How Operator Precedence Works in JavaScript

Operator Precedence in JavaScript

Operator precedence determines the priority in which operations are performed in an expression. When an expression contains multiple operators, JavaScript follows specific rules, such as BODMAS, to decide the order of execution.


What is Operator Precedence?

  • Definition: Precedence refers to the priority level of operators in an expression.

  • Purpose: It helps determine which operation should be performed first.

For example, in the expression (5 + 2) / 7 + 1 * 2, operator precedence decides the sequence of calculations.

General Order of Precedence

  1. Parentheses ()

  2. Exponentiation **

  3. Multiplication *, Division /, Modulus %

  4. Addition +, Subtraction -

When multiple operators have the same precedence level, JavaScript evaluates them from left to right.


Example with Diagram


Sequence for Operators

Operators like *, /, and % have the same priority level. When they appear together, they are evaluated from left to right.

Example Expression

(5 + 2) / 7 + 1 * 2

Step-by-step Solution:

  1. Solve inside the parentheses:

    (5+2)=7(5 + 2) = 7

  2. Perform division and multiplication from left to right:

    7/7=17 / 7 = 1 1∗2=21 * 2 = 2

  3. Perform addition:

    1+2=31 + 2 = 3

Final Result:

The value of the expression is 3.


Examples with Programs

Example 1

Expression:

(2 + 1) * 3

Solution:

  1. Solve inside the parentheses:

    (2+1)=3(2 + 1) = 3

  2. Perform multiplication:

    3∗3=93 * 3 = 9

Final Result: 9

Program:

console.log((2 + 1) * 3); // Output: 9

Example 2

Expression:

3 / 1 + (2 ** 2)

Solution:

  1. Solve the exponentiation:

    2∗∗2=42 ** 2 = 4

  2. Perform division:

    3/1=33 / 1 = 3

  3. Perform addition:

    3+4=73 + 4 = 7

Final Result: 7

Program:

console.log(3 / 1 + (2 ** 2)); // Output: 7

Example 3

Expression:

4 + 1 * 6 / 2

Solution:

  1. Perform multiplication and division from left to right:

    1∗6=61 * 6 = 6 6/2=36 / 2 = 3

  2. Perform addition:

    4+3=74 + 3 = 7

Final Result: 7

Program:

console.log(4 + 1 * 6 / 2); // Output: 7