All lessons

Making Decisions

7 min · JavaScript

Run different code depending on whether something is true.

JavaScript · Making Decisions0/5 cleared

Enemy 1 of 5

This code checks if temperature is above 20 and prints Warm if so, otherwise Cold. Temperature is 5, so press Run and look for Cold in the output.

Why this works

Every program so far has run the same lines in the same order every time. Real programs need to react differently depending on the situation: show a warning only if a score drops too low, apply a discount only if a cart total is high enough. That's what conditionals are for.

An if statement runs the code in its { } block only when its condition evaluates to true; otherwise, that block is skipped entirely. Compare values with operators like > (greater than), < (less than), >= , <= , and === (triple equals, for equality).

JavaScript actually has both === and == for comparing equality. === (strict equality) checks that both value and type match, while == (loose equality) tries to convert the two values to the same type first, which can produce surprising results (like "5" == 5 being true). Almost all modern JavaScript code sticks to === for exactly this reason: it's more predictable, and it's what you should default to.

You
Memory-Leak Rat
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.