Understanding JavaScript Operator Precedence
In JavaScript, operator precedence determines the order in which operators are evaluated in an expression. Understanding operator precedence is crucial for writing correct and efficient code. This tutorial will cover the basics of JavaScript operator precedence, providing detailed explanations and sample codes for different scenarios.
![](https://dumudigitikakenya.com/wp-content/uploads/2024/03/JavaScript-Operator-Precedence-1-1-1024x576.jpg)
Table of Contents
JavaScript Operator Precedence
JavaScript follows a set of rules to determine the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first. If two operators have the same precedence, their evaluation order depends on their associativity.
Operator Precedence Table
JavaScript has various types of operators, each with its own precedence level. Below is a simplified table showing some common operators and their precedence levels:
Precedence | Operator |
---|---|
1 (highest) | () (grouping) |
2 | ! (logical NOT), ++ (postfix), — (postfix) |
3 | *, /, % |
4 | +, – |
5 | <, >, <=, >= |
6 | ==, !=, ===, !== |
7 | && (logical AND) |
8 | || (logical OR) |
9 (lowest) | = (assignment) |
Sample Codes
Let’s go through some sample code snippets to understand how operator precedence works in JavaScript.
Scenario 1: Arithmetic Operations
let result = 5 + 3 * 2;
console.log(result); // Output: 11
Explanation:
- Multiplication (*) has higher precedence than addition (+).
- So,
3 * 2
is evaluated first, resulting in6
. - Then,
5 + 6
is evaluated, resulting in11
.
Scenario 2: Comparison Operators
let result = 10 > 5 + 3;
console.log(result); // Output: true
Explanation:
- Addition (+) has lower precedence than comparison (>).
- So,
5 + 3
is evaluated first, resulting in8
. - Then,
10 > 8
is evaluated, resulting intrue
.
Scenario 3: Logical Operators
let result = (5 > 3) && (10 < 5);
console.log(result); // Output: false
Explanation:
- Comparison operators have higher precedence than logical operators.
- So,
(5 > 3)
and(10 < 5)
are evaluated first. 5 > 3
istrue
, but10 < 5
isfalse
.- Then,
true && false
evaluates tofalse
.
Conclusion
Understanding operator precedence is essential for writing JavaScript code that behaves as expected. By following the rules of operator precedence, you can avoid unexpected outcomes and write more efficient code. Make sure to refer to the operator precedence table whenever you’re unsure about the order of evaluation in complex expressions. Practice writing and analyzing code to solidify your understanding of JavaScript operator precedence.