Dart Operator: Precedence

Dart Operator: Precedence

ยท

1 min read

In Dart, the precedence of operators determines the order in which operations are performed in an expression. Operators with higher precedence are evaluated before operators with lower precedence.

Here's a simple way to understand it:

Imagine you have a math expression like 2 + 3 * 4. The multiplication has a higher precedence than addition, so you perform the multiplication first and then the addition. In Dart, you don't always need parentheses to explicitly specify the order; the language follows predefined rules based on operator precedence.

Here are a few examples:

dartCopy codevoid main() {
  // Example 1:
  int result1 = 2 + 3 * 4;
  print(result1);  // Output: 14

  // Example 2:
  int result2 = (2 + 3) * 4;  // Parentheses can be used to override precedence
  print(result2);  // Output: 20
}

In the first example, 3 * 4 is evaluated first due to the higher precedence of multiplication, and then 2 + (result of multiplication) is calculated.

In the second example, parentheses (2 + 3) are used, indicating that the addition should be performed before the multiplication.

Understanding operator precedence helps you write expressions that are evaluated in the intended order. If in doubt, you can use parentheses to explicitly specify the order of operations.

ย