๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Dart Operators

Operators are signs that compare values or combine truth values. A comparison gives back true or false.

Comparing two numbers

The first test asks if 18 reaches 18 or more. The second test asks if 18 stays below 21.

void main() {
  var age = 18;
  print(age >= 18);
  print(age < 21);
}

Equal and not equal

The equal test matches two fives. The not equal test finds no difference between the same two fives.

void main() {
  print(5 == 5);
  print(5 != 5);
  print(4 == 9);
}

And and or

The and line needs both sides true, so it gives false. The or line needs only one side true, so it gives true.

void main() {
  var hasTicket = true;
  var hasPass = false;
  print(hasTicket && hasPass);
  print(hasTicket || hasPass);
}

Not flips a value

The stored value is false. The not sign flips it, so the printed value is true.

void main() {
  var ready = false;
  print(!ready);
}

Example

void main() {
  var score = 72;
  var passMark = 50;
  var bonus = true;
  print(score >= passMark);
  print(score == 100);
  print(score >= passMark && bonus);
  print(score < passMark || bonus);
}

Key points

  • Equal: a == b asks if two values match.
  • Not equal: a != b asks if two values differ.
  • Greater and less: a > b and a < b compare sizes.
  • Greater or equal: a >= b also passes when the values match.
  • Less or equal: a <= b also passes when the values match.
  • And: a && b is true only when both sides are true.
  • Or: a || b is true when at least one side is true.
  • Not: !a turns true into false and false into true.

In this example, score holds 72 and passMark holds 50. The first print compares 72 with 50 and gives true. The second print compares 72 with 100 and gives false. The third print joins a true comparison with bonus, and both sides are true. The fourth print joins a false comparison with bonus, and one true side is enough.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

What does the sign && need to give true?