Operators & LogicCore· 40 min read

Conditions: if, else & Comparisons

Make your code decide. This is where programs start to feel intelligent.

What you will learn

  • Compare values with comparison operators
  • Branch with if / else if / else
  • Combine conditions with && and ||

Comparison operators

OperatorMeans
===Equal (value AND type) — use this
!==Not equal
> <Greater / less than
>= <=Greater-or-equal / less-or-equal

Watch out: Use === (three equals) to compare. A single = assigns a value — using it in a condition is a classic bug. Prefer === over == because it also checks the type.

if / else if / else

An if checks a condition; if it is true, its line runs. else if offers another condition to try, and else is the catch-all when nothing above matched. JavaScript checks them top to bottom and stops at the first true one.

A grading decision
<script>
  let marks = 72;
  let grade;

  if (marks >= 90)      grade = "A";
  else if (marks >= 75) grade = "B";
  else if (marks >= 60) grade = "C";
  else                  grade = "Fail";

  document.write("Grade: " + grade);
</script>
Live preview

With marks = 72: is 72 ≥ 90? No. Is 72 ≥ 75? No. Is 72 ≥ 60? Yes — so grade becomes "C" and JavaScript skips the rest. That is why the page shows a C.

Note: Output: Grade: C

Combine conditions

&& means AND (both must be true). || means OR (either is enough). ! means NOT.

&& requires both conditions
<script>
  let age = 20, hasID = true;
  if (age >= 18 && hasID) {
    document.write("Entry allowed");
  } else {
    document.write("Entry denied");
  }
</script>
Live preview

The condition age >= 18 && hasID is only true when both sides are true. Here age is 20 (so age >= 18 is true) and hasID is true, so the whole thing is true and the if branch runs. If either were false, the else branch would run instead.

Note: Output: Entry allowed

Q. Which operator checks equality of value AND type?

Answer: === checks both value and type and is the recommended equality operator. = assigns; == compares loosely.

✍️ Practice

  1. Write a script that prints “Pass” if marks are 40 or above, else “Fail”.
  2. Check if a number is positive, negative or zero using if/else if/else.

🏠 Homework

  1. Build a simple grade calculator that turns a score (0–100) into a letter grade.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →