Making Decisions
7 min · JavaScript
Run different code depending on whether something is true.
Enemy 1 of 5
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.
Loading editor...