Skip to main content

Overview

Comparison operators (also called relational operators) are used to compare two values. They always return a boolean value: true or false.

Comparison Operators Table

OperatorDescriptionExampleResult
==Equal to18 == 18true
!=Not equal to18 != 18false
>Greater than18 > 17true
<Less than18 < 18false
>=Greater than or equal to18 >= 18true
<=Less than or equal to18 <= 18true

Basic Example

Here’s a complete example demonstrating all comparison operators:
void main() {
  int edad = 18;

  print(edad == 18);   // Igual: true
  print(edad != 18);   // Diferente: false
  print(edad > 17);    // Mayor que: true
  print(edad < 18);    // Menor que: false
  print(edad >= 18);   // Mayor o igual: true
  print(edad <= 18);   // Menor o igual: true
}
Output:
true
false
true
false
true
true
Comparison operators are essential for control flow statements like if, while, and for loops.

Understanding Equality

Equal (==) vs Not Equal (!=)

int x = 5;
int y = 10;

print(x == y);  // false (5 is not equal to 10)
print(x != y);  // true (5 is different from 10)
In Dart, use == for equality comparison, not =. The single = is the assignment operator!
  • x == 5 checks if x equals 5
  • x = 5 assigns 5 to x

Range Comparisons

Greater Than and Less Than

int score = 85;

print(score > 90);   // false
print(score > 80);   // true
print(score < 100);  // true
print(score < 85);   // false

Inclusive Comparisons

The >= and <= operators include the boundary value:
int age = 18;

print(age >= 18);  // true (18 is included)
print(age > 18);   // false (must be greater, not equal)

print(age <= 18);  // true (18 is included)
print(age < 18);   // false (must be less, not equal)
Use >= and <= when you want to include the boundary value in your comparison. For example, “age must be 18 or older” would use age >= 18.

Practical Examples

Age Verification

int userAge = 20;
bool isAdult = userAge >= 18;
print(isAdult);  // Output: true

Password Length Check

String password = "mypass123";
bool isValidLength = password.length >= 8;
print(isValidLength);  // Output: true

Grade Evaluation

int grade = 75;
bool passed = grade >= 60;
bool excellence = grade >= 90;

print('Passed: $passed');        // Output: Passed: true
print('Excellence: $excellence'); // Output: Excellence: false

Range Checking

int temperature = 22;
bool isComfortable = temperature >= 18 && temperature <= 25;
print(isComfortable);  // Output: true

Build docs developers (and LLMs) love