Home  >  Article  >  Web Front-end  >  operator precedence in js

operator precedence in js

下次还敢
下次还敢Original
2024-05-09 00:45:27529browse

Operator precedence determines the execution order of operators in JavaScript. They are arranged in order of priority from high to low as follows: parentheses () square brackets [] dot. Unary operators multiplication and division addition and subtraction Comparison Operator Logical AND Logical OR Ternary Operator Assignment Operator Comma Operator

operator precedence in js

JavaScript Operator Priority

In JavaScript, the precedence of operators determines the order in which they are executed. When there are multiple operators in the same line of code, the operator with higher precedence will be executed first.

Operator precedence order (from high to low):

  • Parentheses ()
  • Square brackets[]
  • Dot.
  • Unary operators (such as !, -, , --)
  • Multiplication and division (*, /, %)
  • Addition and subtraction (,-)
  • Comparison operations Symbols (==, !=, >, <, >=, <=)
  • ##Logical AND (&&)
  • Logical OR (||)
  • Ternary operator (?:)
  • ##Assignment operator (=, =, -=)
  • comma operator,
Example:

In the following expression, multiplication operation The precedence of the symbol (*) is higher than that of the addition operator ( ):

<code class="js">const result = 2 + 3 * 4; // 结果为 14</code>

And in the following expression, the precedence of parentheses is higher than that of the multiplication operator:

<code class="js">const result = (2 + 3) * 4; // 结果为 20</code>

Note:

If two operators have the same precedence, they are executed from left to right.
  • You can use parentheses to enforce the order of operations.
  • Some operators have left and right associativity. This means they will be executed from left to right or right to left.

The above is the detailed content of operator precedence in js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn