JavaScript if...else

Beginner
5 min read
Updated: Nov 2026
3 examples

Definition and Usage

Use if to run a block when a condition is truthy. Add else for the other path, and else if for more checks. Conditions often use comparisons like === or >.

JavaScript Syntax

JavaScript
const score = 85;
if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else {
  console.log("C");
}
Try it Editor

How It Works

  1. First check fails. 85 is not >= 90.
  2. Second check passes. 85 >= 80, so print B.
  3. else skipped. Only one branch runs.

Examples

Example 1 — Truthy checks

Non-empty strings and non-zero numbers are truthy.

JavaScript
if ("hi") console.log("yes");
if (0) console.log("no");
else console.log("zero is falsy");
Try it Editor

How It Works

  1. Non-empty string is truthy.
  2. 0 is falsy, so else runs.

Example 2 — Nested if

Keep nesting shallow when you can.

JavaScript
const age = 20;
const hasId = true;
if (age >= 18) {
  if (hasId) console.log("enter");
}
Try it Editor

How It Works

  1. Outer condition passes.
  2. Inner condition also passes.

Example 3 — Prefer clear branches

For two short values you may use a ternary later.

JavaScript
const ok = true;
console.log(ok ? "yes" : "no");
Try it Editor

How It Works

  1. Ternary is an expression form of if/else.
  2. See the Operators ternary page for details.

Frequently Asked Questions

A statement that chooses which block of code to run based on a condition.
Use braces {} for every branch. One-line branches without braces are easy to break later.
false, 0, -0, 0n, "", null, undefined, and NaN.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful