Often you want to do one thing if the condition is true, and something else if it's false. That's what else is for:
const age = 15;
if (age >= 18) {
console.log("You can vote! 🗳️");
} else {
console.log(`You can vote in ${18 - age} years.`);
}
It prints
You can vote in 3 years.
Think of it as a fork in the road. JavaScript will take exactly one of the two paths, never both, and never neither. If the condition is true, it runs the first block. Otherwise, it runs the else block.
const password = "open sesame";
const typedPassword = "open sesam";
if (typedPassword === password) {
console.log("Welcome in! 🔓");
} else {
console.log("Wrong password. Access denied! 🔒");
}
It prints
Wrong password. Access denied! 🔒
One missing letter, and you're locked out. Computers are very strict doormen.