Learn JavaScript · lesson 13 of 60 · about 7 minutes
if and else
Let Sam's page do one thing or another: invite visitors who can comment, and tell everyone else why they can't.
What you'll learn
- Write an if statement
- Add an else branch
- Use braces to group code
Different visitors, different page
Sam's page already works out canComment, but every visitor still sees the same page. Someone who can comment should be invited to, and everyone else should be told they can't. The page needs to do one thing or the other.
Making a choice
if (condition) { ... } runs the code inside the braces only when the condition is true. else { ... } runs when it's false.
The condition goes in round brackets; the code goes in curly braces.
Only visitors who can comment are invited
const canComment = true;
if (canComment) {
document.querySelector("#comment-box").textContent = "Leave a comment below!";
} else {
document.querySelector("#comment-box").textContent = "You can't comment right now.";
}if and else
const fuel = 3;
if (fuel > 0) {
console.log("Lesson unlocked");
} else {
console.log("Out of fuel");
}
console.log("Done");Output
Lesson unlocked
DoneTruthy and falsy
The condition doesn't have to be a comparison. false, 0, "" (empty text), null, undefined and NaN all count as false, and everything else counts as true. So if (name) means if there's a name.
Tip
Indent the code inside braces by two spaces. JavaScript doesn't require it, but it makes the structure easy to see.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.