JavaScript If Else

Run code based on conditions.

✍️ 3 exercises + code challenge in this lesson

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";

Key Takeaways: JavaScript If Else

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.

JavaScript If Else Code Example

JavaScript
<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>
Free sign-in required · Google login available

JavaScript If Else Practice Exercises

Check what you learned in “JavaScript If Else”.

/ 3 solved
Fill in the blank

Complete the condition.

 (age >= 18) {
  log("Adult");
}  {
  log("Minor");
}
✓ Correct! Not quite. Try again.
Multiple choice

Which is the ternary operator?

✓ Correct! Not quite. Try again.
Code challenge

If marks is 50 or more, log "Pass", otherwise log "Fail".

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

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