In Ask One Message a Yes-or-No Question and the exercise after it, you asked one message a question and got back a Boolean: true or false. That answer was complete, but it didn’t do anything. Your report needs to act on it, picking a message when the answer is yes and leaving it alone when the answer is no.
By the end of this lesson, you’ll be able to write an if statement that runs code only when a condition holds. You’ll select messages by topic, then by review status, and finally check a suggested rule that requires both.
Run Code Only When the Answer Is Yes
Here’s a billing message, with a question you already know how to ask. This time, the question sits inside an if statement:
> const message = {
… id: 8,
… topic: "billing",
… status: "approved",
… };
undefined
> if (message.topic === "delivery") {
… console.log("Selected message", message.id);
… }
… console.log("Checked message", message.id);
Checked message 8
undefined
This session is for reading. The supplied console.log() calls show which lines ran, and the final undefined only means the input as a whole has no value to report.
An if statement has three parts:
- The keyword
ifstarts the statement. - The condition in parentheses can be a comparison that produces
trueorfalse, like the ones you wrote before. - The block in curly braces holds the code that runs only when the condition is
true.
Here the condition is false, so JavaScript skips the block. The last line still runs: code after the closing brace isn’t an “otherwise” branch. It runs whether the condition is true or false. With message 7, a delivery message, both lines would print.
The two spaces in front of the first console.log() don’t change what runs. The braces decide what belongs to the block. Indentation is for people reading the code, so keep it lined up: one step in after {, and back out for }.