Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript if Statement

The if statement is the simplest way to execute code conditionally in JavaScript.

It runs a block only when a condition evaluates to true.

Why We Need It

Most application logic starts with simple checks like if a user is logged in or if data is valid.

Clear if statements make control flow easy to understand and maintain.

Syntax

if (condition) { ... }

Basic Example

1. Basic if

const isOnline = true;

if (isOnline) {
  console.log("User is online");
}

The block runs only when the condition is true.

Real World Example

2. Guard Clause

function submit(form) {
  if (!form.isValid) return;
  console.log("Submitting...");
}

Guard clauses exit early when a condition fails.

Multiple Use Cases

Single-Branch Decisions

The if statement runs a block only when a condition is true.

Use it for guard clauses, validation, and early returns.

Boolean Expressions

Any expression that evaluates to true or false can be used in an if condition.

Prefer explicit comparisons for clarity.

Readable Guards

Keep if conditions short. Extract complex logic into named variables.

This makes code easier to scan and review.

More Examples

3. Range Check

const age = 19;

if (age >= 18) {
  console.log("Adult");
}

Use comparisons to check ranges.

4. Combine Conditions

const isMember = true;
const total = 120;

if (isMember && total > 100) {
  console.log("Apply discount");
}

Logical operators combine multiple checks.

Comparison

Without

let label = "";
if (isActive) {
  label = "Active";
}

With

const label = isActive ? "Active" : "";

Common Mistakes and Fixes

Overly complex conditions

Extract logic into named booleans for readability.

Using assignment instead of comparison

Use === for comparisons, not =.

Relying on truthy/falsy accidentally

Use explicit comparisons when values can be 0 or empty strings.

Deep nesting

Use guard clauses or return early to keep nesting shallow.

Interview Questions

What does an if statement do?

It runs a block only when a condition is true.

Why use guard clauses?

They reduce nesting and make code easier to read.

What is a truthy value?

Any value that coerces to true in a boolean context.

Practice Problem

Practice: Check if a cart total is above a free-shipping threshold and log a message.

const total = 65;
// TODO: log "Free shipping" only if total >= 50

One Possible Solution

const total = 65;
if (total >= 50) {
  console.log("Free shipping");
}

Frequently Asked Questions

Can I put any expression in if?

Yes, but it will be coerced to a boolean. Explicit comparisons are clearer.

What is a guard clause?

An early return that exits when a condition fails.

Is if faster than switch?

Performance differences are usually negligible. Choose for readability.

Try It Yourself

Try changing the condition to see when the if block executes.