Conditional statements run different code depending on a condition:
if (condition) { ... }else if (otherCondition) { ... }else { ... }
The ternary operator
A short form for simple choices: const label = age >= 18 ? "Adult" : "Minor";
Run code based on conditions.
✍️ 3 exercises + code challenge in this lessonConditional statements run different code depending on a condition:
if (condition) { ... }else if (otherCondition) { ... }else { ... }A short form for simple choices: const label = age >= 18 ? "Adult" : "Minor";
Mastering JavaScript If Else helps you write clean and reliable JavaScript code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
<input id="hour" type="number" min="0" max="23" value="14"> hour
<button onclick="check()">Greet</button>
<p id="out"></p>
<script>
function check() {
const h = Number(document.getElementById("hour").value);
let greeting;
if (h < 12) {
greeting = "Good morning ☀️";
} else if (h < 18) {
greeting = "Good afternoon 🌤️";
} else {
greeting = "Good evening 🌙";
}
const type = h >= 9 && h < 17 ? "office hours" : "outside office hours";
document.getElementById("out").textContent = `${greeting} (${type})`;
}
check();
</script>
Check what you learned in “JavaScript If Else”.
Complete the condition.
(age >= 18) {
log("Adult");
} {
log("Minor");
}
Which is the ternary operator?
If marks is 50 or more, log "Pass", otherwise log "Fail".
Free sign-in required · Google login available
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services