Decisions: The Fork in the Road
Teaching your script how to choose what happens next.
Until now, your scripts have been like a straight road. They do line 1, then line 2, then line 3. But real apps need to make choices. They need a brain to say, "If this happens, do that!"
- How to use the
ifstatement. - How to use the
elsestatement for backup plans. - Comparison signs like > (Greater) and < (Smaller).
This is for students who want to build "Smart" apps. If you want a script that only sends emails on Mondays, or only alerts you if a price is too high, you need this module.
Think about your Morning Routine:
- IF it is raining, THEN take an umbrella.
- ELSE (it's sunny), THEN wear sunglasses.
The computer does the exact same thing! It checks a "Condition" and then picks a path.
To make a choice, the computer compares two numbers. Here are the most common signs:
>: Greater than (Is 10 bigger than 5?)<: Less than (Is 3 smaller than 8?)===: Exactly equal (Is the score exactly 100?)
(Note: We use THREE equals in JS to be super sure!)
Writing a condition is like writing a recipe. You need parentheses () for the check and curly brackets {} for the action.
const score = 85;
if (score > 50) {
// This happens if the check is TRUE
Logger.log("Great job! You passed.");
} else {
// This happens if the check is FALSE
Logger.log("Keep practicing!");
}
}
Copy this and change the myAge number to see different results!
If you run the code with myAge = 12, the computer sees that 12 is NOT greater than 13, so it skips the first part and jumps straight to the else:
Sorry, you are too young. Try a cartoon! 🧸
Click to see common logic traps
1. Single Equals: Do NOT use if (score = 100). A single = is for putting things in boxes. For checking, use ===.
2. Missing Brackets: Every { must have a closing }. If you forget one, the script will get lost!
3. Semicolons: We don't put a semicolon ; after the if (...) line. Action only!
Create a variable called temp. Write a script that logs "It is Hot!" if the temp is above 30, and "It is Cold!" if it's below 30. Test it with different numbers!
Every login screen in the world uses if/else!
IF (password is correct) THEN (show Inbox).
ELSE (show Error Message). You are now building the logic of the internet!
You’ve given your robot the ability to think! By using if and else, your code can now respond to different situations. This is the foundation of all "Smart" technology.
Status: Decision Maker 🚦 | Level: Logic Apprentice 🧠