Programming Basics
If/Else (Conditionals)
The idea, in plain English
An if/else is a fork in the road for your code. Picture a bouncer at a door. IF you are old enough, they let you in. ELSE, they turn you away. The computer checks a yes/no question, called a 'condition'. Then it runs different code depending on the answer.
How it works
- 1Write `if` followed by a question that is true or false, like 'is the temperature below 0?'.
- 2If the answer is true, the code inside that block runs. If it's false, the computer skips to the next check.
- 3Add `else if` for more questions. Add a final `else` to catch 'none of the above'.
When you'd use it
Use if/else whenever your program needs to make a decision. It can do different things depending on the situation. For example, show an error if a field is empty, or give a discount if a cart total is high enough.
Common beginner mistakes
- Using `=` (which sets a value) instead of `==` or `===` (which checks if two values are equal) inside a condition.
- Writing conditions in the wrong order. If you check the broad case before the narrow one, the narrow one never runs.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Expected output — hit Run to try it
-5C is freezing
10C is cold
20C is mild
30C is hotNot sure this is the right topic? See the learning paths → or where this leads →