JavaScriptLesson 4 of 10Jump to practice
Conditions
Run different code depending on a condition with if, else if and else.
Programs make decisions. Conditions let your code take one path or another.
if
if (condition) {
// runs only when the condition is true
}
if and else
<script>
const hour = new Date().getHours();
if (hour >= 9 && hour < 17) {
console.log("The shop is open.");
} else {
console.log("Sorry, we're closed. Open 9am to 5pm.");
}
console.log("It is now hour", hour);
</script>else if: more than two choices
Chain conditions with else if. JavaScript checks them in order and runs the first one that’s true.
<script>
const marks = 74;
let grade;
if (marks >= 80) {
grade = "A+";
} else if (marks >= 70) {
grade = "A";
} else if (marks >= 60) {
grade = "A-";
} else if (marks >= 50) {
grade = "B";
} else if (marks >= 40) {
grade = "C";
} else if (marks >= 33) {
grade = "D";
} else {
grade = "F";
}
console.log(marks + " marks is grade " + grade);
</script>Change marks and run it again. Then try moving the marks >= 40 check to the top. Every passing mark becomes a C, because the first true condition wins. Order matters.
True-ish and false-ish values
A condition doesn’t have to be a comparison. JavaScript treats some values as false:
false, 0, "" (an empty string), null, undefined and NaN.
Everything else counts as true. That gives a handy check for an empty input:
const name = "";
if (name) {
console.log("Hello " + name);
} else {
console.log("Please type your name");
}
The short form
For a simple either-or value, the ternary operator fits on one line:
const label = age >= 18 ? "Adult" : "Child";
Read it as: is age at least 18? If so, “Adult”, otherwise “Child”. Keep it for short choices. For anything bigger, if is easier to read.
Practice
Check what you just learned. Fill in the missing code, then answer the quiz.
Exercise 1Solved
Run the message only when the temperature is above 30.
(temperature > 30) { console.log("Hot day"); }Exercise 2Solved
Run the second block when the condition is false.
if (isLoggedIn) { console.log("Welcome back"); } { console.log("Please log in"); }Exercise 3Solved
Check a second condition when the first one is false.
if (marks >= 80) { grade = "A+"; } (marks >= 70) { grade = "A"; }
Finish the practice to complete this lesson.
Sign in to keep your progress on any device.
