JavaScript If Else
Conditional statements let your program choose which code to run based on whether an expression is true or false.
Making decisions in code
Most useful programs need to react differently depending on their input. Should a shopping cart apply a discount? Is a user old enough to sign up? Has a download finished? To answer questions like these, JavaScript evaluates a condition and then decides which branch of code to execute. The main tools for this are the if, else if, and else statements, along with the shorter ternary operator for simple cases.
- if runs a block only when its condition is true.
- else if tests another condition when the previous ones were false.
- else provides a fallback block that runs when nothing above matched.
- The condition inside the parentheses is always converted to a boolean (true or false).
A basic if...else
<!DOCTYPE html>
<html>
<body>
<h2>A basic if...else</h2>
<script>
const hour = 14;
if (hour < 12) {
console.log("Good morning");
} else if (hour < 18) {
console.log("Good afternoon");
} else {
console.log("Good evening");
}
// Output: Good afternoon
</script>
</body>
</html>JavaScript checks each condition from top to bottom and stops at the first one that is true. Because 14 is not less than 12 but is less than 18, only the afternoon branch runs. Once a branch matches, the remaining branches are skipped entirely, which makes the order of your conditions important.
Truthy and falsy values
The condition does not have to be an explicit comparison. Any value placed inside an if is coerced to a boolean. Values that behave like false are called falsy, and everything else is truthy. Knowing this list helps you write shorter, clearer checks.
The ternary operator for short choices
<!DOCTYPE html>
<html>
<body>
<h2>The ternary operator for short choices</h2>
<script>
const points = 85;
// condition ? valueIfTrue : valueIfFalse
const result = points >= 50 ? "pass" : "fail";
console.log(result); // "pass"
// Handy inside strings
const count = 1;
console.log(`You have ${count} item${count === 1 ? "" : "s"}`);
// "You have 1 item"
</script>
</body>
</html>