agyanadda@gmail.com

JS If Else

Conditions and Loops 1 min read Updated Dec 1, 2026 Topic 13 of 38

Conditions let your code make decisions.

if (marks >= 60) {
  grade = 'First';
} else if (marks >= 45) {
  grade = 'Second';
} else {
  grade = 'Fail';
}
  • if runs its block when the condition is true
  • else if checks another condition
  • else runs when nothing above was true

Only one block runs — the first one whose condition is true.

Combine conditions

if (age >= 18 && hasId) { ... }

Short form

For simple choices use the ternary operator: const msg = age >= 18 ? 'Adult' : 'Minor';

Example

Example — Grade calculator HTML
<input id="marks" type="number" value="72"> 
<button onclick="check()">Get grade</button>
<p id="out"></p>

<script>
  function check() {
    const marks = Number(document.getElementById('marks').value);
    let grade;
    if (marks >= 90) {
      grade = 'A+';
    } else if (marks >= 75) {
      grade = 'A';
    } else if (marks >= 60) {
      grade = 'B';
    } else if (marks >= 33) {
      grade = 'C';
    } else {
      grade = 'Fail';
    }
    document.getElementById('out').textContent = 'Grade: ' + grade;
  }
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which block runs when no condition is true?

Exercise 2 True / False

More than one else if block can run for the same check.

Exercise 3 Fill in the Blank

The condition of an if statement is written inside ___ brackets ( ).

Frequently Asked Questions

Yes, for a single statement, but always using braces avoids bugs when you add more lines later.