B Binance · The world's largest crypto exchangeBinance Sign up → AD OKX OKX · A leading global crypto exchangeOKX Sign up → AD
💻 Coding Basics · Lesson 3 / 10

Conditionals — Taking Different Paths Depending on the Situation

Conditionals are how you write choice, the second ingredient of an algorithm, in code. Most of writing a condition correctly is deciding clearly which way to go right at the boundary.

⏱ About 20 min ✍️ 5 practice questions 🧪 4 code exercises Updated 2026-10-09
🎯 By the end of this lesson you can
  • Write multi-way conditions with if, else if, and else in the right order
  • Build conditions with comparison operators and &&, ||, and !, and explain why you should use === instead of ==
  • Tell truthy and falsy values apart and predict how 0 and the empty string behave in a condition
  • Choose edge values and test whether a conditional behaves correctly

1.`if` and `else` — making a fork in the road

In Lesson 1 we said code runs in order, from top to bottom. A conditional puts a fork in that flow. When you write if (condition) { … }, the code inside the curly braces runs only if the condition in the parentheses is true, and is skipped if it is false. If there is something to do when the condition is false, add else { … } after it. Exactly one of the two branches runs.

In the condition slot you write an expression whose result is true or false. This is where the booleans from Lesson 2 come in. age >= 19 is an expression that is true if age is 19 or more and false otherwise. If you print the condition with console.log first, you can see in advance which way the conditional will go, which helps you find the cause when it does not behave as you meant.

Code inside the curly braces is indented by two spaces so you can see at a glance that it belongs to that condition. The engine ignores indentation and uses the braces, but people read structure through indentation. Misaligned indentation can mislead the reader, so always keep it consistent. Even if there is only one line inside the braces, keeping the braces makes mistakes less likely when you add lines later.

Printing the condition first shows which branch will run
const age = 17;
console.log(age >= 19);
if (age >= 19) {
  console.log("Adult fare");
} else {
  console.log("Youth fare");
}
Output
false
Youth fare

2.`else if` — several branches, checked from the top

When there are three or more branches, chain on else if. The engine checks the conditions one at a time from the top, runs only the first branch whose condition is true, and skips all the rest. If none of the conditions is true, the final else runs. So else is the slot for "everything else that none of the cases above covered."

Because of the "only the first true one" rule, the order of the conditions matters. If you are assigning grades from scores, you must check the highest threshold first. A score of 95 makes both score >= 90 and score >= 80 true, so if you write the 80 condition first, 95 gets a B. If you go down from the highest threshold, each later condition can rely on the fact that the earlier ones were already false, so you do not need to write both ends of the range, as in score >= 80 && score < 90.

Laying the rules out in a table before writing the conditional makes it easy to spot missing ranges and overlapping ones. If you have decided "90 or more A, 80 or more B, 70 or more C, everything else F," as in the example below, just copy what is in the table, from the top. These grade thresholds are only an example; real ones differ from school to school and company to company.

Checking the highest threshold first runs only the first true branch
const score = 85;
if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else if (score >= 70) {
  console.log("C");
} else {
  console.log("F");
}
Output
B
95 points, yet it prints B — the second branch can never be reached
// an example with the order wrong
const s = 95;
if (s >= 80) {
  console.log("B");
} else if (s >= 90) {
  console.log("A");
}
Output
B

3.Comparison operators and `===` vs `==`

The operators that compare two values are greater than (>), less than (<), greater than or equal to (>=), less than or equal to (<=), equal to (===), and not equal to (!==). The result is always true or false. Be careful: if you write only one = when comparing for equality, it is not a comparison but an assignment that puts a value in. This mistake is very common, and in some cases the code behaves wrongly without any error.

JavaScript has two kinds of "equal." === (strict equality) is true only if both the type and the value are the same. == (loose equality) first applies the implicit type coercion from Lesson 2 when the types differ, and then compares. So 1 == "1" is true, and so is 0 == "". The rules are complicated and hard to predict, which is why almost every coding guide and linting tool recommends using only === and !==. This course always uses === too.

You can compare strings as well. === requires every character to match, so "Alex" === "Alex " (with a trailing space) is false. User input often fails to match because of spaces at the beginning or end, which is why Lesson 7 teaches how to clean it up with trim. Using < and > on strings compares them by character code, which is close to dictionary order, but strings that look like numbers compare strangely, as in "10" < "9" being true, so convert them to numbers first.

== converts types before comparing, so results are not what you expect
console.log(3 > 2, 3 >= 3, 3 !== 3);
console.log(1 === "1", 1 == "1");
console.log(0 == "", 0 === "");
console.log(null == undefined, null === undefined);
Output
true true false
false true
true false
true false
Convert strings that look like numbers into numbers before comparing
console.log("Alex" === "Alex ");
console.log("10" < "9", 10 < 9);
console.log(Number("10") < Number("9"));
Output
false
true false
false
Summary of comparison operators
OperatorMeaningExampleResult
===Same type and same value5 === 5true
!==Not equal (strict)5 !== "5"true
> / <Greater than / less than3 < 2false
>= / <=Greater than or equal to / less than or equal to60 >= 60true
==Equal after type coercion (do not use)1 == "1"true

4.Logical operators — and `&&`, or `||`, not `!`

To combine several conditions, use logical operators. A && B is true only when both A and B are true, and A || B is true when at least one of them is true. !A flips true and false. "Is a member and spent 30,000 won or more" is &&; "is a member or spent 30,000 won or more" is ||. Because everyday "and" and "or" are used loosely, it is a good idea to state the condition in words first and then double-check which one you mean.

&& and || do not evaluate the right side if the left side alone settles the answer. In A && B, if A is false the result is false no matter what B is, so B is not looked at; in A || B, if A is true, B is not looked at. You can use this by writing user !== null && user.age >= 19: when user is null, the right side is never read, so you avoid the TypeError from Lesson 2. Swap the order and this protection disappears.

If you mix && and || in one expression, && is evaluated first. But rather than memorizing that precedence, it is much safer to group with parentheses to show your intent. If you write a range the math way, as 10 <= x <= 20, there is no error, but it does not do what you mean. Always split it into two comparisons, as in x >= 10 && x <= 20.

Conditions for a hypothetical online shop
const isMember = false;
const total = 32000;
console.log(isMember && total >= 30000);
console.log(isMember || total >= 30000);
console.log(!isMember);
Output
false
true
true
10 <= x becomes true first, and true <= 20 turns into 1 <= 20, which is true
const x = 25;
console.log(10 <= x <= 20); // does not work as meant
console.log(x >= 10 && x <= 20);
Output
true
false

5.Truthy and falsy — non-boolean values work as conditions too

Putting a non-boolean value in the parentheses of an if does not cause an error. JavaScript converts the value to true or false and decides from that. The values treated as false (falsy) are a fixed list: false, 0, -0, 0n, the empty string "", null, undefined, and NaN. Every value not on this list is treated as true (truthy). People often get confused by the fact that the empty array [], the empty object {}, and the strings "0" and "false" are all truthy.

Thanks to this, you can write "if there is a value" briefly as if (name) { … }. But there is a trap. In counts and amounts, 0 is a perfectly normal value, yet it is falsy. If you check a product with 0 in stock using if (stock), "no stock information" and "0 in stock" end up in the same branch. It is a mistake you often see in AI-written code too.

So when you know exactly what you want to check, write the condition specifically. To see whether a value is missing, write stock === null or stock === undefined; to see whether it is greater than 0, write stock > 0; to see whether it is the empty string, write name === "". If you want to know whether a value is truthy, you can check it directly with Boolean(value).

"0" and the empty array are truthy
console.log(Boolean(0), Boolean(""), Boolean(null));
console.log(Boolean(NaN), Boolean(undefined));
console.log(Boolean("0"), Boolean("false"));
console.log(Boolean([]), Boolean(-1));
Output
false false false
false false
true true
true true
To treat 0 as a normal value, write the condition specifically
const stock = 0;
if (stock) {
  console.log("Available");
} else {
  console.log("No stock info?"); // 0 in stock lands here
}
if (stock === null) {
  console.log("No stock info");
} else if (stock > 0) {
  console.log("Available");
} else {
  console.log("Sold out");
}
Output
No stock info?
Sold out

6.Edge values — conditionals go wrong at the boundary

Most bugs in conditionals happen at the boundary. If you write "60 or more passes" as score > 60, a score of 60 fails. Testing only with 59 and 61 will never catch this mistake. So when checking a conditional, always try the value just below the boundary, the boundary itself, and the value just above it. Add the smallest value (0), the largest value (100), and values that should never come in (negative numbers, more than 100), and most mistakes will show up.

The boundary has to be clear from the moment you state the rule in words. In "19 or older," "free shipping on 30,000 won or more," and "discount for more than 10 items," "or more" and "or older" mean >=, "more than" means >, "or less" means <=, and "less than" or "under" means <. If a requirement is vague, such as "from 30,000 won," the right thing to do is to confirm which side exactly 30,000 won falls on before you write any code. When you ask AI for code, stating the boundaries clearly in words also makes the result much more accurate.

If you put the values to check in a table, they become your test cases as they are. That is exactly what the grader in this course's playground does: it feeds in predefined inputs and compares the results with the expected values. Once you learn functions in Lesson 5, such tests become even easier to write, and in Lesson 10 you will use this method to verify code written by AI.

Test values for checking "60 or more passes" (scores 0–100)
InputWhy it was chosenExpected resultIf written wrongly as `score > 60`
59Just below the boundaryFailFail
60The boundary itselfPassFail (bug found)
61Just above the boundaryPassPass
0 / 100Smallest / largest valueFail / PassFail / Pass
-5 / 120Values that should never come inHandled as an invalid scoreFail / Pass (no check)
ExampleA hypothetical online shop rule: "Shipping is 0 won if the order total is 30,000 won or more or the customer is a member; otherwise it is 3,000 won." Choose test values for this rule and check the results with code.
const orders = [[29999, false], [30000, false], [0, true]];
for (const [total, isMember] of orders) {
  let fee = 3000;
  if (total >= 30000 || isMember) {
    fee = 0;
  }
  console.log(total, isMember, fee);
}
Output
29999 false 3000
30000 false 0
0 true 0
  1. Step 1 Find the boundaries: the boundary for the amount is 30,000 won, and "or more" means >=. Membership has two cases, true and false.
  2. Step 2 Choose test values: 29,999 won and 30,000 won for a non-member, plus 0 won for a member (to see whether a member gets free shipping even on a tiny amount).
  3. Step 3 Write the condition: if total >= 30000 || isMember is true, the fee is 0; otherwise it is 3000.
  4. Check: only 29,999 won for a non-member should give 3,000 won, and the rest should give 0 won. If 30,000 won gives 3,000 won, > was used by mistake.
Answer29,999 won (non-member) → 3000, 30,000 won (non-member) → 0, 0 won (member) → 0
The for … of in the example code is a loop you will learn in Lesson 4, and a list in square brackets like [29999, false] is an array you will learn in Lesson 6. const [total, isMember] is syntax that puts the first and second values of that list into two names in turn. For now, just notice the idea of taking the cases out one by one and feeding each into the same conditional.

📌 Key points

  • if, else if, and else are checked from the top and only the first true branch runs — order matters
  • Always use === and !== to compare for equality — == converts types first and is hard to predict
  • && means all true, || means at least one true, ! flips; write ranges split up, as in x >= 10 && x <= 20
  • Falsy values include false, 0, "", null, undefined, and NaN; when 0 is a normal value, write the condition specifically
  • Test conditionals with the value just below the boundary, the boundary, just above it, both extremes, and invalid values

✍️ Practice questions

Answer first, then open "Answer and explanation".

Q1. With const s = 95;, what does if (s >= 80) {…B…} else if (s >= 90) {…A…} print?

⭕ Correct

❌ Not quite — see the explanation

Answer and explanation
Answer ② B

Only the first true branch runs. For 95, s >= 80 is already true, so it prints B and the second branch is not even checked. The highest threshold must come first.

Q2. Which of these is true?

⭕ Correct

❌ Not quite — see the explanation

Answer and explanation
Answer ③ 1 == "1"

== converts the string "1" to a number before comparing, so it is true. === is false when the types differ. Because == is so hard to predict, we use ===.

Q3. Which of these values is NOT falsy (that is, truthy)?

⭕ Correct

❌ Not quite — see the explanation

Answer and explanation
Answer ③ "0"

The string "0" is not an empty string, so it is truthy. The number 0, the empty string, and null are falsy.

Q4. When testing a conditional that checks "19 or older counts as an adult," which three ages must you include?

⭕ Correct

❌ Not quite — see the explanation

Answer and explanation
Answer ② 18, 19, 20

Just below the boundary (18), the boundary itself (19), and just above it (20). If 19 does not come out as an adult, > was used by mistake.

Q5. Write a condition that checks whether x is between 10 and 20, inclusive.

Answer and explanation
Answer x >= 10 && x <= 20

10 <= x <= 20 compares the result of the first comparison (true or false) with 20 again, so it does not work as intended. You must join the two comparisons with &&.

🧪 Code lab

In these exercises you complete functions with conditionals. The grader tries several inputs, including edge values.

Your code runs only inside an isolated sandbox in this browser and is never sent to a server. It has no network access and is stopped after 2 seconds. Edited code is saved only in this browser. Ctrl+Enter (⌘+Enter) runs it; Tab inserts two spaces (press Esc, then Tab, to move on).

JavaScript is off, so the code can't run here, but you can still read each task, its starter code, the automatic checks and a sample solution.

1Is this person an adult?

isAdult(age) returns true if the age age (a number) is 19 or more, and false otherwise.

Automatic checks
  • isAdult(18)expected false
  • isAdult(19)expected true
  • isAdult(20)expected true
  • isAdult(0)expected false
💡 Hint

"Or more" includes the boundary. Try 19.

Show a sample solution
function isAdult(age) {
  return age >= 19;
}

2Grade from a score

grade(score) takes a score from 0 to 100 and returns "A" for 90 or more, "B" for 80 or more, "C" for 70 or more, and "F" otherwise.

Automatic checks
  • grade(100)expected "A"
  • grade(90)expected "A"
  • grade(89)expected "B"
  • grade(70)expected "C"
  • grade(69)expected "F"
  • grade(0)expected "F"
💡 Hint

Check the highest threshold first. When the function reaches return it ends immediately, so later conditions are not looked at.

Show a sample solution
function grade(score) {
  if (score >= 90) {
    return "A";
  } else if (score >= 80) {
    return "B";
  } else if (score >= 70) {
    return "C";
  } else {
    return "F";
  }
}

3Shipping fee

A hypothetical online shop rule: shippingFee(total, isMember) returns 0 if the order total total is 30000 or more or the customer is a member (isMember is true), and 3000 otherwise. However, if the order total is 0 or less (an empty order), return 0 regardless of membership.

Automatic checks
  • shippingFee(29999, false)expected 3000
  • shippingFee(30000, false)expected 0
  • shippingFee(5000, true)expected 0
  • shippingFee(0, false)expected 0
  • shippingFee(1, false)expected 3000
💡 Hint

Filter out the empty order first, then check total >= 30000 || isMember.

Show a sample solution
function shippingFee(total, isMember) {
  if (total <= 0) {
    return 0;
  }
  if (total >= 30000 || isMember) {
    return 0;
  }
  return 3000;
}

4Admission fees and invalid input

Admission fees for a hypothetical museum: ticketPrice(age) returns 0 for under 7, 3000 for 7 or older but under 19, 6000 for 19 or older but under 65, and 0 for 65 or older. If the age is negative or not a number (typeof age !== "number"), return null.

Automatic checks
  • ticketPrice(6)expected 0
  • ticketPrice(7)expected 3000
  • ticketPrice(19)expected 6000
  • ticketPrice(65)expected 0
  • ticketPrice(-1)expected null
  • ticketPrice("20")expected null
💡 Hint

If you check typeof age !== "number" || age < 0 at the very start, the later conditions only deal with valid numbers. "Under" is <.

Show a sample solution
function ticketPrice(age) {
  if (typeof age !== "number" || age < 0) {
    return null;
  }
  if (age < 7) {
    return 0;
  } else if (age < 19) {
    return 3000;
  } else if (age < 65) {
    return 6000;
  }
  return 0;
}

🤖 Try asking AI like this

Copy a prompt and replace the [ ] parts with your own situation. Don't take the answer on trust — check it against this lesson.

Before turning a rule into a conditional

I want to turn the following rule into a JavaScript conditional. Before writing any code, first ask me about anywhere the boundaries (or more, more than, or less, less than) are unclear, and then lay out every case in a table of inputs and expected results. Make each row of the table a test case. Rule: [description of the rule]

When reviewing a conditional an AI wrote

Check the conditional below, one item at a time, for (1) branches that can never be reached because of the `else if` order, (2) uses of `==`, (3) places that wrongly filter out 0 or the empty string as falsy, and (4) boundaries that differ from the rule. For each problem, also give me an input value that exposes it. Rule: [rule] Code: [paste code]

When you want to practice truthy and falsy

Make 10 prediction problems about JavaScript truthy/falsy values and `===`/`==` comparisons. Phrase each one as a question about which branch `if (value)` takes, keep the answers hidden, and when I answer, tell me whether I was right and why.

🧰 Related tools

Tools for checking and tidying the JSON, regular expressions and text from this lesson. Don't paste real personal data or passwords.

References
  • MDN Web Docs — JavaScript Guide: Control flow and error handling (if...else), Expressions and operators
  • MDN Web Docs — glossary entries for Falsy and Truthy, and Equality comparisons and sameness
  • General material from introductory software testing books on boundary value analysis

Reached every goal above? Mark the lesson complete.

💻 Coding Basics

  1. 1What Is a Program? — Breaking Work into Sequence, Choice, and Repetition
  2. 2Values, Variables, and Types — Putting Name Tags on Values
  3. 3Conditionals — Taking Different Paths Depending on the Situation
  4. 4Loops — Doing the Same Thing Many Times, Exactly
  5. 5Functions — Splitting Work into Small Named Machines
  6. 6Arrays and Objects — Storing and Handling Data
  7. 7Strings and Text — Cutting, Finding and Replacing Characters
  8. 8Debugging and Reading Errors — Turning Red Text into Clues
  9. 9Simple Automation — Spreadsheet Math and Text Cleanup in Code
  10. 10Reading and Verifying AI-Written Code — Tests, Security, Licenses, Privacy
📚 Worth reading
📊Using AI for Spreadsheets, and Checking the Formulas→ 💻AI Coding Assistants: Security and Licence Risks→ 💬Practising Conversation in a Foreign Language with AI→ ⚙️Finding Work Tasks Worth Automating with AI→
← Foundations for the AI Era