자바스크립트 연산자 우선순위(Operator Precedence)

In JavaScript, operators are used to perform different kinds of operations on values or variables. These operators have a specific order of precedence, which determines the order in which the operations are evaluated. Understanding operator precedence is important to ensure that expressions are evaluated correctly.

Operator Precedence Levels

JavaScript has various operators, such as arithmetic, logical, assignment, and comparison operators. Each operator has a precedence level assigned to it. Operators with higher precedence are executed before operators with lower precedence.

It’s worth noting that parentheses can be used to override the default precedence and explicitly specify the order of evaluation.

Here is a list of operator precedence levels, from highest to lowest:

  1. Grouping operator: ()
  2. Increment and decrement: ++, --
  3. Logical NOT: !
  4. Multiplication, division, and remainder: *, /, %
  5. Addition and subtraction: +, -
  6. Relational and comparison operators: <, >, <=, >=, ==, !=, ===, !==
  7. Logical AND: &&
  8. Logical OR: ||
  9. Conditional (ternary) operator: ? :
  10. Assignment operators: =, +=, -=, *=, /=, %=

It’s essential to understand the precedence levels when multiple operators are used in a single expression. For example:

let result = 10 - 2 * 3;
console.log(result); // Output: 4

In the above example, the multiplication operator * has a higher precedence than the subtraction operator -. So, the expression 2 * 3 is evaluated first, resulting in 6. Then, 10 - 6 is evaluated, giving us the final result of 4.

Conclusion

By understanding operator precedence in JavaScript, you can write expressions that are evaluated correctly and ensure that your code behaves as expected. Always keep the precedence levels in mind, and use parentheses when necessary to override the default order of evaluation.

Remember, taking the time to understand operator precedence will help you become a more proficient JavaScript developer. Happy coding!