If...Else: Making Decisions
Teach your code to choose different paths based on conditions — the most fundamental building block of program logic.
Step 1 of 5
Why does code need to make decisions?
So far, your programs have been a straight line — every instruction runs, top to bottom, every time. But real software constantly adapts. YouTube shows different recommendations based on what you've watched. A weather app displays a sun icon or a rain icon depending on the forecast. A login form shows a welcome message or an error. All of these require the program to *choose* between different code paths based on some condition.
This is what `if...else` gives you: the ability to say 'IF this condition is true, do this; OTHERWISE, do that.' It turns your straight-line program into a choose-your-own-adventure book.
Think of it this way: if...else is like standing at a fork in the road. You check the signpost (the condition), and it tells you which path to take. If the sign says 'Bridge Open,' you cross the bridge. Otherwise, you take the detour. The signpost doesn't change the roads — it just decides which one you walk down.
Web Standard
The if...else statement has been part of JavaScript since its very first version in 1995. Its syntax is shared with C, Java, and many other languages — once you learn it in JavaScript, you'll recognize it everywhere.
Learn more on MDN