“If it’s raining, take an umbrella. If it’s sunny, leave it at home.” This kind of judgment we make every day is something you can write into a program with the if statement. Changing what happens based on the situation—this is the real mechanism behind a program acting “clever.”
The basic shape
let weather = "rain";
if (weather === "rain") {
console.log("Let's bring an umbrella!");
}Since the contents of weather are “rain,” the console shows “Let’s bring an umbrella!” If the contents were “sunny,” nothing would happen.
| Part | Meaning |
|---|---|
if | The signal for “if it’s…” |
Inside ( ) | The condition (an expression checked for whether it holds) |
Inside { } | What to do when the condition holds |
”Equal” is three equals signs
When you check “whether they’re equal” inside a condition, you line up ===, three equals signs.
if (weather === "rain") {When it’s not, use else
You can also write “when it doesn’t hold, do this instead.” That’s else (otherwise).
if (weather === "rain") {
console.log("Let's bring an umbrella!");
} else {
console.log("No umbrella needed!");
}With this, if it’s raining, “Let’s bring an umbrella!”; otherwise, “No umbrella needed!” Because the path splits into two, this mechanism is called “conditional branching.”
You can also compare which number is bigger
Conditions can also include comparisons of numbers.
let score = 85;
if (score >= 80) {
console.log("Amazing! You passed!");
}| How to write | Meaning |
|---|---|
a === b | a and b are equal |
a !== b | a and b are not equal |
a > b | a is greater than b |
a >= b | a is greater than or equal to b |
a < b | a is less than b |
a <= b | a is less than or equal to b |
“Not equal” is written !==. The exclamation mark at the front means “not.”
The true nature of a condition is true and false
By the way, how does an if know whether a condition holds? Actually, the expression you write inside the ( ) turns into one of two answers: true (it holds) or false (it doesn’t). You can check this in the console.
console.log(3 > 1);
console.log(3 > 100);“true” and “false” show up. What an if does is “if the answer is true, run the { }”—it’s that simple a mechanism.
Let’s see it in action
When you combine it with the “events” you learned before, you can make a gadget like this. The reply changes depending on whether the password matches. There’s one new tool: the text typed into an input field can be pulled out by adding .value to the element you grabbed.
Summary of this lesson
- With
if (condition) { what to do }, it runs only when the condition holds - “Equal” is
===(three equals signs). One=means “put in,” so it’s a different thing - With
else, you can also prepare “the path for when it’s not the case”