completefrontend
Open lab My progress
THE JAVASCRIPT FIELD GUIDE

if, else & conditions

Run code only when a condition is true, choose exactly one branch, and simplify decisions with blocks, truthy checks, and early returns.

By the end, you'll be able to
  • 01
    Choose one pathRead an if / else if / else chain and say which branch will run.
  • 02
    Use blocks safelyKnow which lines the braces control, why leaving braces out causes bugs, and where a name made inside a block can be used.
  • 03
    Write clearer checksUse truthy checks when they fit, and use early returns instead of ifs nested inside ifs.

Make decisions with code

A program does not always run every line. Sometimes it has to choose. For example, it may need to:

  • Greet a user who is signed in, but ask a guest to sign in.
  • Show a warning only when a form is not filled in.

JavaScript makes these choices with conditionals. A conditional checks a condition: a question with a yes or no answer. Then it picks which code to run.

The short version

An if statement asks a yes-or-no question. If the answer is yes, JavaScript runs the code inside its braces. If the answer is no, JavaScript skips that code. Then it may try an else if or an else.

Greet a user or ask them to sign inPop out in the code editor (opens in a new tab)JavaScript
const isLoggedIn = false; if (isLoggedIn) {  console.log("Welcome back");} else {  console.log("Please sign in");}

Line 1 sets isLoggedIn to false. Line 3 asks: is isLoggedIn true? It is not, so JavaScript skips line 4. It runs the else part on line 5 instead, and line 6 prints Please sign in. Change line 1 to true, and the program prints Welcome back instead.

The else part is the fallback. It runs only when the if condition above it is false.

The box isLoggedIn holds false. One arrow, marked true, goes to "Welcome back", which is skipped. The other arrow, marked false, goes to "Please sign in", which runs.if (isLoggedIn)falseisLoggedIntrue"Welcome back"skippedfalse"Please sign in"runs
The condition is the value in isLoggedIn. It is false, so JavaScript skips the if path and takes the else path.
Real-life analogyAn if statement is a fork in the road

You walk along a path and reach a sign. If the sign says the bridge is closed, you take the side path. If not, you keep walking straight. The sign only decides which path you take next. An if statement works the same way.

In real life: A sign that says “Bridge closed”
In JavaScript: The condition, like bridgeClosed
In real life: Taking the side path
In JavaScript: Running the code inside if (...) { ... }
In real life: Walking straight on when the bridge is open
In JavaScript: Skipping that code

You already met the tools that conditions are built from: booleans, comparisons, logical operators, ?? and ?., the ternary operator, and blocks. This lesson puts them together. A comparison or a logical operator usually makes the condition. A block holds the code that should run. If truthy and falsy values feel unclear, go back to Booleans & truthiness.

if, else if, else: the first true branch wins

STEP THROUGH

Each possible path in a conditional is called a branch. The most common shape is a chain of branches:

  • JavaScript checks the first condition.
  • If it is false, JavaScript checks the next else if.
  • If every condition is false, the last else runs.

Each time the chain runs, only one branch runs.

Choose a delivery messagePop out in the code editor (opens in a new tab)JavaScript
const orderTotal = 120; if (orderTotal >= 100) {  console.log("free delivery");} else if (orderTotal >= 50) {  console.log("standard delivery");} else {  console.log("delivery fee");}

Line 3 asks: is the total 100 or more? For 120 the answer is yes. So line 4 prints free delivery, and JavaScript skips the other two branches.

Try other totals. For 70, line 3 is false and line 5 is true, so it prints standard delivery. For 20, both checks are false, so the else on line 7 runs and prints delivery fee.

orderTotal is 70. The first check, orderTotal >= 100, is false, so JavaScript moves down to the second check. orderTotal >= 50 is true, so it prints "standard delivery". The else is never reached.orderTotal = 70orderTotal >= 100falseorderTotal >= 50true"standard delivery"elsenever reached
JavaScript checks from the top. The first check is false, so it moves down. The second check is true, so that branch runs and the chain ends. The else is never reached.

Now step through the temperature example. Pick a temperature for line 1. Guess which condition will be the first true one. Then step through and watch JavaScript skip every branch after it.

Follow an if / else if chain
Step 0 of 6Ready
Your turn: follow the blue line

Guess which branch will run. Then step through the conditions until the first true one wins.

Running in
  1. script
Next: line 1
let clothing; if (temperature < 0) {  clothing = "heavy coat";} else if (temperature < 15) {  clothing = "jacket";} else if (temperature < 30) {  clothing = "t-shirt";} else {  clothing = "stay cool";}console.log(clothing);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Change line 1: what is the temperature?

Picking a temperature starts the run again. Guess the first true condition before you step.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
Real-life analogyAn else-if chain works like a mail-sorting machine

A letter slides down a sorting machine. It drops into the first slot that matches its label. Once a local letter falls into the local slot, it never reaches the "everything else" bin at the bottom.

In real life: The first slot catches letters going abroad
In JavaScript: The first if condition
In real life: The second slot catches local letters
In JavaScript: The next else if condition
In real life: The letter drops into the first slot that fits
In JavaScript: The first true branch runs
In real life: Later slots never see that letter
In JavaScript: Later branches are skipped

Try the same idea as a sorting game. For each temperature, which branch would run?

Which branch runs?
  • temperature is -4
  • temperature is 0
  • temperature is 14
  • temperature is 15
  • temperature is 29
  • temperature is 30
  • temperature is 38
  • temperature is -12
Try it yourself
0 of 8 correct

Sort each temperature into the message that the if / else if / else chain picks.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

The order of the checks matters: put narrow checks first

INTERACTIVE

An else-if chain stops at the first true condition. So the order of the checks changes the result. A wide check is true for many values. It can catch a value before a narrower check gets a turn.

Look at this grade function. score >= 50 is true for a score of 91. If that check comes first, the function returns pass. The score >= 90 check never runs.

The order of checks in an else-if chain
function grade(score) {  if (score >= 50) return "pass";  if (score >= 90) return "excellent";  return "try again";}
Resultsbuggy
score45
grade(score)try again
score50
grade(score)pass
score72
grade(score)pass
score91
grade(score)pass
Try it yourself

Wrong order: for a score of 91, score >= 50 is checked first. It is true, so the function returns pass. The excellent check never runs.

Each row of the table comes from calling the real grade function from this lesson.
Rule of thumb

Put the narrowest and most special cases first. Put the wide, catch-all cases last. You did the same in the Comparisons and Logical operators lessons: write the condition that says exactly what you mean.

Blocks: braces mark which lines the if controls

SAFETY

A block is code between curly braces, { and }. In an if statement, the block holds the code for that branch. Every line inside the braces runs only when the condition is true.

With braces, the if controls both linesPop out in the code editor (opens in a new tab)JavaScript
const isAdmin = true;if (isAdmin) {  console.log("show admin link");  console.log("delete account enabled");}

JavaScript also lets you write an if without braces. Then the if controls only the one statement right after it. Indenting a line (moving it right with spaces) does not change this, because JavaScript ignores indenting. That makes this bug easy to miss:

Without braces, line 4 always runsPop out in the code editor (opens in a new tab)JavaScript
const isAdmin = false;if (isAdmin)  console.log("show admin link");  console.log("delete account enabled");
isAdmin is false. Left, with braces: both lines are inside the braces, so nothing prints. Right, without braces: only "show admin link" belongs to the if. "delete account enabled" is not in the if, so it prints.if (isAdmin) { }show admin linkinside the bracesdelete account enabledinside the bracesnothing printsif (isAdmin)show admin linkbelongs to the ifdelete account enablednot in the ifline 4 prints
In both halves isAdmin is false. With braces, the if controls both lines, so nothing prints. Without braces, it controls only the first line. The second line always runs, even though it is indented.
Watch for a semicolon right after the condition

if (isAdmin); is a whole if statement. The semicolon ends it, so its body is empty: it controls nothing. The block after it is just a normal block, so it always runs. The Statements, comments & semicolons lesson warned about this one small character.

Blocks also limit where let and const names can be used. A name made inside an if block exists only inside that block. This is called block scope. The Scope lessons later cover it in depth.

A name made inside a block stays inside itPop out in the code editor (opens in a new tab)JavaScript
const isMember = true; if (isMember) {  const message = "member price";  console.log(message);}

isMember is true, so the block runs. Line 4 makes message, and line 5 prints member price. You can use message inside these braces, but not after them.

So when only one branch needs a value, make it inside that branch. Don't reuse one vague name all through a function.

Truthy conditions: a condition does not have to be a boolean

INTERACTIVE

You can put any value inside if (...). JavaScript turns it into a yes or a no. A value that counts as yes is truthy. A value that counts as no is falsy.

The main falsy values are false, 0, "" (empty text), null, undefined, NaN, and 0n. Almost every other value is truthy.

Check whether a cart has itemsPop out in the code editor (opens in a new tab)JavaScript
const cart = []; if (cart.length > 0) {  console.log("show checkout");} else {  console.log("show empty cart");}

Line 1 makes cart an empty array. An empty array is still truthy, because every array is an object, and every object is truthy. So if (cart) would run even for an empty cart. It can't tell you whether the cart has items.

That is why line 3 asks about the number of items instead. cart.length is 0, so cart.length > 0 is false. Line 6 prints show empty cart.

Left: if (cart) with an empty cart. The empty array is still truthy, so the block runs anyway. Right: if (cart.length > 0). The length is 0, 0 > 0 is false, so the program shows the empty cart.if (cart)[ ]truthy: it runsif (cart.length > 0)cart.length is 00 > 0falseshows empty cart
An empty array is still an object, and every object is truthy. So if (cart) runs even for an empty cart. cart.length > 0 asks the real question: is anything in it?

Now pick a value below and see which branch it chooses.

Test truthy and falsy values
truthy-test.jsPop out in the code editor (opens in a new tab)JavaScript
const value = "0"; if (value) {  console.log("branch runs");} else {  console.log("branch skipped");}
Condition resulttruthy
value"0"
Boolean(value)true
printedbranch runs
clearer checkvalue !== ""
Try it yourself

"0" is truthy, so the program prints "branch runs". In real code, a clearer check might be value !== "".

Each button picks one ready-made JavaScript value and shows which branch really runs.

The table below compares short truthy checks with checks that say exactly what they mean. Read each row as: "when I write this, JavaScript asks this question, and this is when it's a good choice."

Short truthy checks compared with exact checks
When you writeWhat JavaScript asksWhen to use it
if (name)Is name truthy? An empty string, null, and undefined all skip the block.Good for text that must be filled in, when empty means missing.
if (items)Is the array truthy? Even an empty array, [], runs the block.Usually too vague for arrays. It's like asking "Do you have a bag?" when you mean "Is anything in it?"
if (items.length > 0)Does the array hold at least one item?Clear when you need to know whether it's empty.
if (value !== undefined)Was any value given at all?Clear when 0 or "" are allowed values.
Be exact when zero or empty is allowed

If 0 is a real count, if (count) treats it as missing by mistake. Use if (count !== undefined) or if (count >= 0) instead. Pick the one that matches your real rule.

Write the question you really mean

A comparison such as cart.length > 0 already gives a boolean: true or false. So it makes a clear condition when your question is "does this cart have an item?" The if statement then uses that answer to pick a branch.

Text from a form is not a numberPop out in the code editor (opens in a new tab)JavaScript
const accessCode = "5"; if (accessCode === 5) {  console.log("open settings");} else {  console.log("enter a number");}

What a user types into a text box usually reaches your code as a string (text). Here accessCode is the string "5", not the number 5.

Strict equality, ===, checks both the value and the type. A string and a number are different types. So line 3 is false, and the program prints enter a number. Use === for exact comparisons. Turn form text into a number with Number() only when your rule really needs a number.

You can also put a value straight into the condition. if (user) is a short way to ask whether there is a user, because null and undefined are falsy. But it does not prove that the user object has every property your next line needs. When one property matters, check it directly, like user.isAdmin === true.

Think about what the value means before you use the short form. For example:

  • A name that must be filled in can use if (name), because an empty name should be rejected.
  • A discount of 0 is different. Zero can be a real discount, so if (discount) asks the wrong question. Use discount !== undefined to tell a missing discount apart from a zero discount.
Use a short condition only when it asks the right question

Pick the condition another person could read out loud. if (items.length > 0) means "there are items". if (items) only means "there is an array". Both are valid JavaScript, but they ask different questions.

Comparisons from the previous lesson help here. They show the rule in the code, and they give a boolean. The next reader can see why the branch runs without guessing.

Early returns: handle the stop cases at the top

STEP THROUGH

Functions get their own module next, but you can read this pattern now. return leaves a function right away. An early return uses this to handle a stop case, like a missing user, near the top of the function. Each of these early checks is called a guard clause.

Real-life analogyEarly returns work like a ticket check at the door

At a concert, a guard checks tickets at the door. People with a problem are stopped right there. They don't walk all the way to the stage first. Guard clauses do the same in a function.

In real life: No ticket? You stop at the door.
In JavaScript: if (!user) return "Sign in first";
In real life: Banned from the hall? You stop at the door.
In JavaScript: if (user.blocked) return "Account blocked";
In real life: Everyone who gets past the door may go in
In JavaScript: The last return, for success

Below are two versions of the same checkout function. One uses nested ifs: an if inside an if inside an if. The other uses early returns. Pick a shopper and step through both.

Nested ifs or early returns?
Step 0 of 8Ready
Your turn: follow the blue line

Switch between nested ifs and early returns. Both give the same result, but the path through the code is different.

Running in
  1. script
Next: line 8
function checkout(user) {  if (!user) return "Sign in first";  if (user.blocked) return "Account blocked";  if (user.cartItems === 0) return "Cart is empty";  if (!user.paymentReady) return "Add payment method";  return "Ready to checkout";}const result = checkout(user);console.log(result);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Pick a version of the function
Pick a shopper

Changing either choice starts the run again. Compare both versions with the same shopper.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Both versions give the same result for every shopper in the experiment. The early-return version is often easier to read. Each problem is handled in one line, and then it is done. The success line stays at the left edge, instead of being pushed right by many levels of braces.

Where you'll use this

Conditionals show up wherever code reacts to data. Here are common uses:

  • Show a loading, empty, error, or success message.
  • Check a form before sending it.
  • Choose a price, a delivery option, or a permission message.
  • Return early from a function when a needed value is missing.
A function that picks one checkout messagePop out in the code editor (opens in a new tab)JavaScript
function statusMessage(user, cart) {  if (!user) return "Please sign in.";  if (cart.length === 0) return "Your cart is empty.";  if (!user.paymentReady) return "Add a payment method.";  return "Ready to checkout.";} const user = { paymentReady: true };const cart = ["tea"];console.log(statusMessage(user, cart));

Line 2 stops guests before the function reads their cart. Line 3 handles a signed-in shopper with an empty cart. Line 4 handles a missing payment method. If the code reaches line 5, every check above it was false, so the shopper is ready.

Lines 8 and 9 make a signed-in shopper with tea in the cart. So line 10 prints Ready to checkout. Each return gives the screen one clear message.

In a real app, keep the checks close to the data they need. Don't write a long chain just because you can. When a decision has its own name, like "can this user check out?", put it in its own function. Use a ternary only to pick one small value inside an expression.

The table below says which tool fits which job. Read each row as: "when I need to do this, this tool fits best, and this is why."

Which tool to use: if/else, the ternary, or early returns
When you need toBest toolWhy
Pick one small valueThe ternaryconst label = open ? "Open" : "Closed" is short and easy to read.
Run several statementsif / elseA block can hold many lines: logs, returns, and assignments.
Handle many cases in orderif / else if / elseYou can see the order of the checks, and the first true one wins.
Stop bad input to a functionEarly returnsGuard clauses stop the code from nesting deeper and deeper.

Common misconceptions

“Every true condition in an else-if chain runs.”

No. Only the first true branch runs. Then the whole chain is done.

“Indenting decides what the if controls.”

Indenting only helps people read. JavaScript looks at the braces. Without braces, the if controls only the next statement.

“Truthy means equal to true.”

"0" and [] are both truthy, but neither one is the boolean true. Truthy only means the value counts as yes in a condition.

“Every if needs an else.”

An if can stand alone. Add an else only when there is a real fallback to run.

“Early returns are only for errors.”

They are for any case you can finish early: no user, an empty cart, no permission, or a job that is already done.

Practice: choose the right path

5 EXERCISES
Exercise 1 · Warm-upPredict the branch

What word does this program print? Type it exactly.

Starter codePop out in the code editor (opens in a new tab)JavaScript
const loggedIn = true;
const hasCart = false;

if (loggedIn && hasCart) {
  console.log("checkout");
} else if (loggedIn) {
  console.log("browse");
} else {
  console.log("sign in");
}

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeFix the grade bug: the checks are in the wrong order

    grade(95) should print excellent, but this version prints pass. Change the order of the checks to fix it.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    function grade(score) {
      if (score >= 50) return "pass";
      if (score >= 90) return "excellent";
      return "try again";
    }
    console.log(grade(95));

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeRewrite nested ifs with early returns

      Write the checkout function with guard clauses. Check these cases in order: no user, a blocked account, an empty cart, and a missing payment method. If none of them match, return the success message.

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      function canCheckout(user) {
        if (!user) return "Sign in first";
        if (user.blocked) return "Account blocked";
        if (user.cartItems === 0) return "Cart is empty";
        if (!user.paymentReady) return "Add payment method";
        return "Ready to checkout";
      }
      console.log(canCheckout(null));
      console.log(canCheckout({ blocked: false, cartItems: 2, paymentReady: true }));
        Exercise 4 · PracticeFix the missing-braces bug

        Which line still prints when isAdmin is false? Then add braces so that neither admin-only line runs.

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        const isAdmin = false;
        if (isAdmin)
          console.log("show admin link");
          console.log("delete account enabled");

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeWrite a ticket price by age

          Write ticketPrice(age) with these prices:

          • Under 5: free, so 0.
          • Under 18: 8.
          • 65 or older: 6.
          • Everyone else: 12.
          Starter codePop out in the code editor (opens in a new tab)JavaScript
          function ticketPrice(age) {
            if (age < 5) return 0;
            if (age < 18) return 8;
            if (age >= 65) return 6;
            return 12;
          }
          console.log(ticketPrice(3));
          console.log(ticketPrice(16));
          console.log(ticketPrice(40));
          console.log(ticketPrice(70));

          Answer, then press Check. Spacing and letter case don’t matter.

            Quiz: check your understanding

            7 QUESTIONS

            Work through each piece of code line by line. Your first answer counts toward your score, and every answer explains why.

            Lesson quiz · 7 questionsScore: first tries count
            1. Question 1 of 7Temperature check: what does this print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const temp = 20;
              if (temp < 0) {
                console.log("coat");
              } else if (temp < 30) {
                console.log("t-shirt");
              } else {
                console.log("cool");
              }

              Choose an answer to see the explanation.

            2. Question 2 of 7In an else-if chain, what happens after the first true condition?

              Choose an answer to see the explanation.

            3. Question 3 of 7A string as a condition: what does this print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              if ("0") {
                console.log("runs");
              } else {
                console.log("skips");
              }

              Choose an answer to see the explanation.

            4. Question 4 of 7Why are braces useful around the code of an if?

              Choose an answer to see the explanation.

            5. Question 5 of 7A semicolon after the condition: what does this print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              const isAdmin = false;
              if (isAdmin);
              {
                console.log("danger");
              }

              Choose an answer to see the explanation.

            6. Question 6 of 7A function must reject bad input at the top. Which shape is usually clearer?

              Choose an answer to see the explanation.

            7. Question 7 of 7An exact length check: what does this print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              function label(items) {
                if (items.length > 0) return "has items";
                return "empty";
              }
              console.log(label([]));

              Choose an answer to see the explanation.

            Key takeaways

            • if runs its block only when its condition is truthy.
            • In an else if chain, the first true branch runs, and the rest are skipped.
            • Braces mark the block that the condition controls. They also keep let and const names inside that block.
            • Truthy checks are handy. For arrays, zero, and missing values, an exact check is clearer.
            • Early returns handle the stop cases first and keep a function easy to read.

            Remember the one-liner.
            Conditionals let JavaScript choose which code to run.

            Up next: The switch statement.

            CompleteFrontend Clear concepts. Working examples.