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

This code checks if temperature is above 20. It is not, so the else part runs and prints Cold. Press Run to see it.

Why this works

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…
Sign up to fightThis one runs on our servers, so it needs a free account.