Learn to make decisions in your code using if, else if, else, switch statements, and the ternary operator.
Conditional statements let your code make decisions. The most fundamental is the if / else statement:
const temperature = 30;
if (temperature > 25) {
console.log('It is hot outside!');
} else {
console.log('It is not that hot.');
}The condition inside the parentheses is evaluated as a boolean. If it is truthy, the first block runs. If it is falsy, the else block runs (if provided).
Key rules:
().{}.else clause is optional.When you need to check multiple conditions, use else if to chain them:
const score = 85;
if (score >= 90) {
console.log('Grade: A');
} else if (score >= 80) {
console.log('Grade: B');
} else if (score >= 70) {
console.log('Grade: C');
} else {
console.log('Grade: F');
}Conditions are checked from top to bottom. The first one that is true executes, and the rest are skipped.
For matching a variable against specific values, a switch statement can be cleaner:
const day = 'Monday';
switch (day) {
case 'Monday':
case 'Tuesday':
console.log('Start of the week');
break;
case 'Friday':
console.log('Almost weekend!');
break;
default:
console.log('Just another day');
}Don't forget the break keyword — without it, execution "falls through" to the next case. The default case runs when no other case matches.
<p id="weather">Checking weather...</p>
<script>
const temperature = 22;
const weather = document.getElementById('weather');
if (temperature >= 35) {
weather.textContent = 'Extreme heat! Stay indoors.';
} else if (temperature >= 25) {
weather.textContent = 'It is warm and sunny.';
} else if (temperature >= 15) {
weather.textContent = 'Pleasant weather, enjoy!';
} else if (temperature >= 5) {
weather.textContent = 'It is chilly, grab a jacket.';
} else {
weather.textContent = 'Freezing! Bundle up.';
}
</script>The ternary operator is a shorthand for simple if/else assignments. It uses the syntax:
condition ? valueIfTrue : valueIfFalseExamples:
const age = 20;
const status = age >= 18 ? 'adult' : 'minor';
// status is 'adult'
const score = 75;
const passed = score >= 60 ? 'Pass' : 'Fail';
// passed is 'Pass'The ternary operator is great for concise, simple conditions. However, avoid nesting ternaries or using them for complex logic — an if/else statement will be more readable in those cases.
// Avoid this — hard to read
const result = a > b ? a > c ? 'a wins' : 'c wins' : b > c ? 'b wins' : 'c wins';
// Use if/else instead for complex logicWhat will `if (0) { 'yes' } else { 'no' }` evaluate to?