Running Code Only When a Condition Holds
Introduction
Welcome to Making Decisions and Repeating Work in JavaScript! In the earlier courses, we gave JavaScript instructions and stored values that those instructions could use. The program followed every line in order. Now we will teach it to skip some lines when they do not apply.
We will learn how an if statement checks a condition, how braces mark the lines that depend on that condition, and how else gives the program a second path. By the end, we will decide whether the Corner Cafe can serve a customer based on whether the shop is open and whether any cups remain.
A Condition with if
A condition is an expression that answers a yes-or-no question. Comparisons such as stockCount === 0 produce either true or false. An if statement uses that answer to decide whether a block of code should run. Here is a small example:
When we run this program, the condition is false, so the first message is skipped and the final message still appears:
The condition goes in parentheses after if. The opening brace begins the block, and the closing brace ends it. The two spaces before the line inside the block are called indentation. Indentation does not change the answer, but it makes it easy to see which line belongs to the choice. We use two spaces consistently. JavaScript also allows an if to control one statement without braces, but in this course we keep braces around conditional blocks to group the statements and make the structure visible.
In this course, we use comparisons that produce boolean answers. JavaScript can also evaluate other values in an if; we will leave those truthy and falsy cases for later. Equality checks like stockCount === 0 ask whether two values match, while comparisons like stockCount > 20 ask whether one number is larger. The result is decided before JavaScript enters the block. What matters is that the parentheses contain a complete expression and the braces contain the statements controlled by it.
If we change the count to zero, the same condition becomes true. The message inside the braces runs before the line after the block:
Now the output includes both messages:
The final console.log is outside the braces, so it runs whether the condition is true or false. Keeping braces around each conditional block groups its statements and clearly shows where the block ends.
The if block can hold more than one statement. If the cafe needs to print a warning and a suggested action, both lines can sit inside the same braces and both run together when the condition is true. We should keep the statements for one outcome inside its block, then close the brace before continuing with code that should always run. This boundary helps us predict the whole program: check the condition, run or skip the block, then continue after it.
