All lessons

Making Decisions

7 min · Dart

Run different code depending on whether something is true.

Dart · Making Decisions0/5 cleared

Enemy 1 of 5

if / else and comparisons

An if statement lets your program take different paths depending on a condition — an expression that evaluates to true or false. The code inside the if's { } block only runs when the condition is true; the code inside an attached else block runs otherwise, covering every case the if didn't.

Comparisons use the standard operators: > , < , >= , <= for ordering, and == for equality. That's a double equals sign for comparison — a single = is assignment, used to store a value in a variable, and confusing the two (writing if (number = 0) instead of if (number == 0)) is a classic beginner error in every C-family language, Dart included. Fortunately, Dart's strict typing catches this particular mistake at compile time in most cases, since = returns the assigned value rather than a boolean, which usually doesn't type-check inside an if condition.

Dart requires the condition to actually be a boolean (true or false) — unlike JavaScript or PHP, values like 0 or an empty string are not automatically treated as false. This stricter behavior avoids a category of subtle bugs common in more loosely-typed languages.

You
Memory-Leak Rat

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Cold