# Conditional Statements

Course: [JavaScript](https://www.devtutorials.ai/learn/javascript) · Section: Basics
Source: https://www.devtutorials.ai/learn/javascript/basics/conditional-statements

> Making decisions with if, if...else, else if and nested if, matching one value against many cases with switch, and producing a value with the ternary operator.

## What Is a Conditional Statement?

**Conditional statement** = code that runs only when a condition is true.

- `if`: run this when the condition is true.
- `else`: otherwise, run this.
- `switch`: pick one case from many.

**Simple lesson:** conditionals let your program make choices, like a shopkeeper deciding what to say.

### A Real-World Example

A product card shows **In stock** when stock is above 5.
It shows **Only 2 left!** when stock is 1 to 5.
It shows **Sold out** when stock is 0, and hides the Buy button.

<figure className="ts-fig">
  <svg viewBox="0 0 560 180" role="img" aria-label="A stock value reaches a fork. If stock is above 5 the path leads to In stock, if 1 to 5 to Only a few left, otherwise to Sold out." width="100%">
    <rect x="0" y="0" width="560" height="180" rx="12" fill="#f8fafc" stroke="#e2e8f0" />
    <rect x="20" y="70" width="100" height="40" rx="8" fill="#eff6ff" stroke="#2563eb" />
    <text x="70" y="95" textAnchor="middle" fontSize="13" fontFamily="monospace" fill="#1e40af">stock = 2</text>
    <polygon points="200,90 240,60 280,90 240,120" fill="#fefce8" stroke="#ca8a04" />
    <text x="240" y="94" textAnchor="middle" fontSize="11" fill="#854d0e">if?</text>
    <line x1="120" y1="90" x2="200" y2="90" stroke="#94a3b8" strokeWidth="2" />
    <line x1="280" y1="90" x2="380" y2="35" stroke="#94a3b8" strokeWidth="2" />
    <line x1="280" y1="90" x2="380" y2="90" stroke="#16a34a" strokeWidth="3" />
    <line x1="280" y1="90" x2="380" y2="145" stroke="#94a3b8" strokeWidth="2" />
    <rect x="380" y="18" width="160" height="34" rx="8" fill="#f0fdf4" stroke="#16a34a" />
    <text x="460" y="40" textAnchor="middle" fontSize="12" fill="#166534">&gt; 5 → In stock</text>
    <rect x="380" y="73" width="160" height="34" rx="8" fill="#fef3c7" stroke="#d97706" />
    <text x="460" y="95" textAnchor="middle" fontSize="12" fill="#92400e">1–5 → Only 2 left!</text>
    <rect x="380" y="128" width="160" height="34" rx="8" fill="#fee2e2" stroke="#dc2626" />
    <text x="460" y="150" textAnchor="middle" fontSize="12" fill="#991b1b">else → Sold out</text>
    <circle r="6" cx="120" cy="90" fill="#2563eb">
      <animate attributeName="cx" values="120;200;280;380" keyTimes="0;0.35;0.6;1" dur="3s" repeatCount="indefinite" />
    </circle>
  </svg>
  <figcaption>The value travels down only one road: the first condition that is true.</figcaption>
</figure>

Every box runs when you press **Run**. Edit a value and run again to see a different branch.

## What You Will Learn

1. `if`, `if...else` and `else if` chains.
2. Nested `if`, and flatter guard clauses.
3. `switch`, `break` and `default`.
4. The ternary `? :` for small choices.

## if statement

The block in `{ }` runs only when the condition is true.

```js runnable title="The message prints only when the cart has items"
const itemsInCart = 2;
if (itemsInCart > 0) {
  console.log("Ready to check out");
}
console.log("Done");
```

Expected output:

```text
Ready to check out
Done
```

The condition does not have to be a boolean. Truthy values count as true:

```js runnable title="A name and an empty string, used directly as conditions"
const name = "Asha";
const coupon = "";
if (name) {
  console.log("Hello,", name);
}
if (coupon) {
  console.log("Coupon applied");
}
```

Expected output:

```text
Hello, Asha
```

## if...else statement

`else` runs when the condition is false. Exactly one of the two blocks runs.

```js runnable title="Free delivery over 499, a delivery charge otherwise"
const total = 320;
if (total >= 499) {
  console.log("Free delivery");
} else {
  console.log("Delivery: ₹40");
}
```

Expected output:

```text
Delivery: ₹40
```

## else if

Checks run from the top. The **first** true one wins, and the rest are skipped.

```js runnable title="Stock turned into a label, one condition at a time"
const stock = 2;
if (stock > 5) {
  console.log("In stock");
} else if (stock > 0) {
  console.log(`Only ${stock} left!`);
} else {
  console.log("Sold out");
}
```

Expected output:

```text
Only 2 left!
```

So the order matters. Put the strictest check first:

```js runnable title="The same labels in the wrong order, and every product looks plentiful"
const stock = 2;
if (stock > 0) {
  console.log("In stock");
} else if (stock > 5) {
  console.log("Plenty left");
} else {
  console.log("Sold out");
}
```

Expected output:

```text
In stock
```

## nested if

An `if` inside another `if` checks the second thing only when the first is true.

```js runnable title="The discount is checked only after the account is confirmed"
const isSignedIn = true;
const isMember = true;
if (isSignedIn) {
  if (isMember) {
    console.log("10% member discount");
  } else {
    console.log("Join to save 10%");
  }
} else {
  console.log("Please sign in");
}
```

Expected output:

```text
10% member discount
```

Deep nesting is hard to read. A **guard clause** returns early instead:

```js runnable title="The same checks, written flat with guard clauses"
function discountMessage(isSignedIn, isMember) {
  if (!isSignedIn) return "Please sign in";
  if (!isMember) return "Join to save 10%";
  return "10% member discount";
}
console.log(discountMessage(true, true));
console.log(discountMessage(false, true));
```

Expected output:

```text
10% member discount
Please sign in
```

## switch statement

`switch` compares one value against many `case`s with `===`.

- `break` leaves the switch.
- `default` runs when no case matches.

```js runnable title="One order status matched against four cases"
const status = "shipped";
switch (status) {
  case "pending":
    console.log("We got your order");
    break;
  case "shipped":
    console.log("On the way");
    break;
  case "delivered":
    console.log("Enjoy!");
    break;
  default:
    console.log("Unknown status");
}
```

Expected output:

```text
On the way
```

Forget `break`, and the code **falls through** into the next cases:

```js runnable title="A missing break makes three messages print instead of one"
const status = "pending";
switch (status) {
  case "pending":
    console.log("We got your order");
  case "shipped":
    console.log("On the way");
  case "delivered":
    console.log("Enjoy!");
}
```

Expected output:

```text
We got your order
On the way
Enjoy!
```

Fall-through is useful when two cases share one answer:

```js runnable title="Saturday and Sunday share one branch"
const day = "Sunday";
switch (day) {
  case "Saturday":
  case "Sunday":
    console.log("Weekend sale: 20% off");
    break;
  default:
    console.log("Regular prices");
}
```

Expected output:

```text
Weekend sale: 20% off
```

## Conditional (ternary) operator (?:)

For a choice between two **values**, a ternary is shorter than `if...else`.

```js runnable title="Picking a word for a message with one ternary"
const count = 1;
const word = count === 1 ? "item" : "items";
console.log(`You have ${count} ${word} in your cart`);
```

Expected output:

```text
You have 1 item in your cart
```

Nested ternaries are hard to read. Use an `if` chain for three or more choices:

```js runnable title="A nested ternary and the if chain that says the same thing"
const stock = 0;
const label = stock > 5 ? "In stock" : stock > 0 ? "Few left" : "Sold out";
console.log(label);

let same;
if (stock > 5) same = "In stock";
else if (stock > 0) same = "Few left";
else same = "Sold out";
console.log(same);
```

Expected output:

```text
Sold out
Sold out
```

## Conditionals on a Web Page

Pick a label and a colour from the stock, and hide the Buy button when it is sold out. Change `stock` to `8`, `3` and `0`.

```js runnable preview="price-card" title="A product card that changes with the stock"
const stock = 3;
const stockLine = document.querySelector("#stock");
document.querySelector("#name").textContent = "Steel bottle";
document.querySelector("#price").textContent = "₹299";

if (stock > 5) {
  stockLine.textContent = "In stock";
  stockLine.style.color = "green";
} else if (stock > 0) {
  stockLine.textContent = `Only ${stock} left!`;
  stockLine.style.color = "darkorange";
} else {
  stockLine.textContent = "Sold out";
  stockLine.style.color = "crimson";
}

const buy = document.createElement("button");
buy.textContent = "Buy now";
buy.disabled = stock === 0;
document.querySelector("#card").append(buy);
console.log("label:", stockLine.textContent, "| buy enabled:", !buy.disabled);
```

**Easy way to remember:** an `if` chain is a queue. The first true condition gets served, and everyone after it goes home.

## TL;DR

- `if` runs a block when the condition is true; `else` covers the rest.
- In an `else if` chain only the first true branch runs, so order matters.
- Guard clauses (`if (!ok) return ...`) keep code flat.
- `switch` uses `===`. Every case needs `break`, unless you want fall-through.
- Use `? :` to choose between two values.

## Try this

In the **switch** example, change `status` to `"Shipped"` with a capital S. It prints `Unknown status`, because `===` treats upper and lower case as different.

## Check Yourself

## Common mistakes

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| `if (stock = 0)` | `=` compares | Use `===` to compare | The value is changed and the check is wrong |
| `> 0` before `> 5` in a chain | All true branches run | Only the first true branch runs | Later branches never run |
| A `case` with no `break` | Each case stops by itself | Code falls into the next case | Several messages print |
| `case "1":` for the number `1` | `switch` converts types | `switch` uses `===` | The case never matches |
| `if (items)` when `items` is `[]` | An empty array is false | `[]` is truthy | The empty-cart message never shows |

## Quick reference

<div className="tscroll">

| Syntax | Meaning |
|---|---|
| `if (condition) { ... }` | run the block only when the condition is truthy |
| `if (condition) { ... } else { ... }` | run exactly one of the two blocks |
| `else if (condition) { ... }` | test another condition; the first true one wins |
| `if (a) { if (b) { ... } }` | a nested `if`: `b` is checked only after `a` passes |
| `if (!ok) return;` | a guard clause that leaves early instead of nesting |
| `switch (value) { case x: ...; break; }` | compare one value against exact cases with `===` |
| `default:` | the block that runs when no case matches |
| `condition ? a : b` | give back `a` when the condition is truthy, otherwise `b` |

</div>

## Exercises

## What to Remember

- Conditionals choose which code runs.
- Order an `else if` chain from the strictest check to the loosest.
- `switch` for one value against many cases; `? :` for two values.

Next: **Loops**. Run the same code again and again, once for each item.
