Programming Concepts · Chapter 2 · Control Flow

2.1 Conditionals

How to make your program choose — run this code or that code, depending on the data it sees.


bookSHelf  ·  Introduction to Programming Concepts  ·  §2.1  ·  a self-paced section

Titlepage: double rule over the sans title, one-sentence lede, hairline rule, small-print byline. Paper-white, link-blue accent, zero radius.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

Outline — by the end of this section you will be able to

Learning Objectives

  1. Write an if statement that runs code only when a condition is true if
  2. Add an else clause to run code when a condition is false else
  3. Chain multiple conditions with else if else if
  4. Use the conditional (ternary) operator ? to pick a value ternary
  5. Decide when to use if vs. the ? operator judgment
Five objectives, one per click. The tag column names the tool each objective teaches.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.1 — The fundamental decision-maker

The “if” Statement

The if statement is how we tell JavaScript to run some code only when a certain condition is true.

if (condition) {
  // code that runs only if condition is true
}

The condition goes inside parentheses (). If it is true, the code inside the curly braces {} runs. If it is false, JavaScript skips that block entirely.


Example: Ask the user what year ECMAScript-2015 was published, then check the answer.

let year = prompt('In which year was ECMAScript-2015 specification published?', '');

if (year == 2015) console.log('You are right!');
The if statement is the simplest conditional. The condition goes in parentheses, the body in curly braces. The example shows a real prompt-and-check.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

Context Pause — why braces matter

Always use curly braces

The curly braces {} group multiple statements into one block. Even if you only have one statement, using braces makes your code easier to read and less likely to break when you add more later.

Without braces (fragile)

if (year == 2015)
  console.log("That's correct!");
  console.log("You're so smart!"); // always runs!

With braces (safe)

if (year == 2015) {
  console.log("That's correct!");
  console.log("You're so smart!");
}
Without braces, only the first statement after if is conditional. The second statement always runs — a common bug. Braces prevent this.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.1 — Worked example

Example 2.1.1: Checking a Number

Example 2.1.1 — Checking a Number

Write an if statement that checks whether a variable temperature is greater than 30. If it is, show "It's hot outside!".

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Since 35 is greater than 30, the condition is true and the message prints.

Commit-first: the prompt shows, then one click reveals the full solution below a hairline rule.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.1 — Practice

Try It Now 2.1.1

Try It Now 2.1.1

Declare a variable score and set it to 85. Write an if statement that shows "Great job!" when score is greater than or equal to 70.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Since 85 is greater than or equal to 70, the condition is true and the message prints.

Students should try this in their browser console before clicking to reveal the solution.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.1 — Worked example

Example 2.1.2: One Equals Sign, or Three?

Example 2.1.2 — One Equals Sign, or Three?

There are three, not two. One = stores a value. Two == asks a question, ignoring type. Three === asks a question, including type. The trap: JavaScript lets you put the storing one inside an if. Predict what this prints before you run it.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

It prints Perfect score! — and then 100. The condition never asked a question: score = 100 stored 100 and handed that back to the if, which is truthy. The variable was changed on the way past.

This is the classic misuse: using the ternary to call functions instead of returning a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.1 — Practice

Try It Now 2.1.2

Try It Now 2.1.2

prompt() always hands back a string, even when the user types digits. Declare year as the string "2015", then log year === "2015", year === 2015, and typeof year. Predict each line first.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Same type and value, so the first is true. The second is false: year holds a string, and a string is not a number however alike they look. When a comparison surprises you, check the types before you change the comparison.

This is the classic misuse: using the ternary to call functions instead of returning a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.2 — How JavaScript decides true or false

Boolean Conversion

The if (...) statement evaluates whatever is inside the parentheses and converts it to a boolean — either true or false.

Falsy values (become false)

0
""   (empty string)
null
undefined
NaN
false

Truthy values (become true)

1, -1, 3.14   (any non-zero number)
"hello"        (any non-empty string)
[]             (any array)
{}             (any object)
true
JavaScript has exactly six falsy values. Everything else is truthy. This is why if (0) never runs and if (1) always does.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.2 — The central idea

Definition: Truthy and Falsy

Definition 2.1.1 — Truthy and Falsy

A falsy value is one that becomes false when converted to a boolean. A truthy value is one that becomes true when converted to a boolean.

if (0) { ... }  // never runs — 0 is falsy
if (1) { ... }  // always runs — 1 is truthy

Definition 2.1.1: Truthy and Falsy.

We can also store the boolean in a variable first: let cond = (year == 2015); if (cond) { ... }

The definition sits in a ruled paper box. The clarifying line reveals on click as the takeaway.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

Insight Note — a common beginner pattern

Don’t write if (x == true)

Beginners often write if (x == true) — but that is redundant. If x is already a boolean, just write if (x). If x is not a boolean, the if converts it automatically.

Redundant

if (x == true) {
  console.log("yes");
}

Idiomatic

if (x) {
  console.log("yes");
}
The if statement already converts its condition to boolean. Writing == true is like asking "is it true that it's true?" — unnecessary.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.2 — Worked example

Example 2.1.3: Testing Falsy Values

Example 2.1.3 — Testing Falsy Values

What will this code show?

let name = "";

if (name) {
  console.log("Hello, " + name);
} else {
  console.log("No name entered.");
}

Answer: The empty string "" is falsy, so the condition name is false. The else block runs, showing "No name entered."

The empty string is one of the six falsy values. The else branch catches it.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.2 — Practice

Try It Now 2.1.3

Try It Now 2.1.3

Declare a variable itemsInCart and set it to 0. Write an if statement that shows "Your cart is empty" when itemsInCart is falsy. Remember that 0 is falsy.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Since 0 is falsy, the else block runs and you see "Your cart is empty."

0 is falsy, so the if condition fails and the else branch runs.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.3 — The other side of the branch

The “else” Clause

An if statement can have an optional else block. The else block runs when the condition is falsy.

let year = prompt('In which year was the ECMAScript-2015 specification published?', '');

if (year == 2015) {
  console.log('You guessed it right!');
} else {
  console.log('How can you be so wrong?');
}

Every if that has an else guarantees that exactly one of the two blocks will run.

If-else is a binary fork: one path or the other, never both, never neither.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.3 — Worked example

Example 2.1.4: Even or Odd

Example 2.1.4 — Even or Odd

Write code that checks whether a number is even. If it is, show "Even". Otherwise, show "Odd".

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

The % operator gives the remainder. If num % 2 is 0, the number is even. Since 8 divided by 2 has remainder 0, you see "Even".

The modulo operator % gives the remainder. Even numbers have remainder 0 when divided by 2.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.3 — Practice

Try It Now 2.1.4

Try It Now 2.1.4

Declare a variable age and set it to 16. Write an if...else statement that shows "You can vote" if age is 18 or older, and "Too young to vote" otherwise.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Since 16 is less than 18, you see "Too young to vote".

A real-world use of if-else: age-gating for voting eligibility.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1 — Figure 2.1.1

The fork, drawn

An if...else is one question with two labelled exits. Whichever branch runs, the program ends up in the same place.

Pairs with Example 2.1.4.

Figure 2.1.1 The student submitted a flowchart diagram. Mermaid source: ```mermaid flowchart TD n1([Start]) n2[set num to 8] n3{num % 2 == 0} n4["print #quot;Even#quot;"] n5["print #quot;Odd#quot;"] n6([End]) n1 --> n2 n2 --> n3 n3 -- yes --> n4 n3 -- no --> n5 n4 --> n6 n5 --> n6 ``` Shape-by-shape walk (6 shapes, 6 arrows): - n1 Terminal (start/end oval) labelled "Start" — goes to "set num to 8". - n2 Task (rectangle) labelled "set num to 8" — goes to "num % 2 == 0". - n3 Decision (diamond) labelled "num % 2 == 0" — on "yes" goes to "print "Even""; on "no" goes to "print "Odd"". - n4 Task (rectangle) labelled "print "Even"" — goes to "End". - n5 Task (rectangle) labelled "print "Odd"" — goes to "End". - n6 Terminal (start/end oval) labelled "End" — no outgoing arrow. yes no Start set num to 8 num % 2 == 0 print "Even" print "Odd" End

Figure 2.1.1

The modulo operator % gives the remainder. Even numbers have remainder 0 when divided by 2.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.4 — More than two branches

Several Conditions: “else if”

What if we have more than two possibilities? We can chain conditions using else if.

let year = prompt('In which year was the ECMAScript-2015 specification published?', '');

if (year < 2015) {
  console.log('Too early...');
} else if (year > 2015) {
  console.log('Too late');
} else {
  console.log('Exactly!');
}

JavaScript checks each condition in order and stops at the first true one. You can have as many else if blocks as you need.

else if chains let you test multiple conditions in order. The first true condition wins.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

Context Pause — why order matters

Put the most specific conditions first

JavaScript stops checking as soon as it finds a true condition. If a general condition comes before a specific one, the specific one never runs.

Wrong order

if (score >= 60) { console.log("D"); }
else if (score >= 90) { console.log("A"); }
// "A" students get "D"!

Correct order

if (score >= 90) { console.log("A"); }
else if (score >= 80) { console.log("B"); }
else if (score >= 70) { console.log("C"); }
else if (score >= 60) { console.log("D"); }
else { console.log("F"); }
Always check the most restrictive condition first. If you check >= 60 before >= 90, a score of 95 matches the first branch and never reaches the second.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.4 — Worked example

Example 2.1.5: Grade Letter

Example 2.1.5 — Grade Letter

Write code that takes a numeric score and shows a letter grade: 90+ is "A", 80+ is "B", 70+ is "C", 60+ is "D", below 60 is "F".

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Since 85 is greater than or equal to 80 but less than 90, you see "B".

The grade-letter example is the classic else-if chain. Order from highest to lowest.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.4 — Practice

Try It Now 2.1.5

Try It Now 2.1.5

Declare a variable time set to 14 (2:00 PM). Write an if...else if...else chain that shows: "Morning" if time < 12, "Afternoon" if time < 18, "Evening" otherwise.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Since 14 is less than 18 but not less than 12, you see "Afternoon".

Time-of-day classification is a natural fit for else-if chains.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1 — Figure 2.1.2

The staircase, drawn

An else if chain is a staircase of diamonds. A score only reaches the next question by failing the one above it.

Pairs with Example 2.1.5.

Figure 2.1.2 The student submitted a flowchart diagram. Mermaid source: ```mermaid flowchart TD n1([Start]) n2[set score to 85] n3{"score >= 90"} n4["print #quot;A#quot;"] n5{"score >= 80"} n6["print #quot;B#quot;"] n7{"score >= 70"} n8["print #quot;C#quot;"] n9{"score >= 60"} n10["print #quot;D#quot;"] n11["print #quot;F#quot;"] n12([End]) n1 --> n2 n2 --> n3 n3 -- yes --> n4 n3 -- no --> n5 n5 -- yes --> n6 n5 -- no --> n7 n7 -- yes --> n8 n7 -- no --> n9 n9 -- yes --> n10 n9 -- no --> n11 n4 --> n12 n6 --> n12 n8 --> n12 n10 --> n12 n11 --> n12 ``` Shape-by-shape walk (12 shapes, 15 arrows): - n1 Terminal (start/end oval) labelled "Start" — goes to "set score to 85". - n2 Task (rectangle) labelled "set score to 85" — goes to "score >= 90". - n3 Decision (diamond) labelled "score >= 90" — on "yes" goes to "print "A""; on "no" goes to "score >= 80". - n4 Task (rectangle) labelled "print "A"" — goes to "End". - n5 Decision (diamond) labelled "score >= 80" — on "yes" goes to "print "B""; on "no" goes to "score >= 70". - n6 Task (rectangle) labelled "print "B"" — goes to "End". - n7 Decision (diamond) labelled "score >= 70" — on "yes" goes to "print "C""; on "no" goes to "score >= 60". - n8 Task (rectangle) labelled "print "C"" — goes to "End". - n9 Decision (diamond) labelled "score >= 60" — on "yes" goes to "print "D""; on "no" goes to "print "F"". - n10 Task (rectangle) labelled "print "D"" — goes to "End". - n11 Task (rectangle) labelled "print "F"" — goes to "End". - n12 Terminal (start/end oval) labelled "End" — no outgoing arrow. yes no yes no yes no yes no Start set score to 85 score >= 90 print "A" score >= 80 print "B" score >= 70 print "C" score >= 60 print "D" print "F" End

Figure 2.1.2

The modulo operator % gives the remainder. Even numbers have remainder 0 when divided by 2.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.5 — A shorter way to pick a value

Conditional Operator ‘?’

Sometimes we need to assign one of two values to a variable depending on a condition. The conditional operator ? (also called the ternary operator) lets us do that in a shorter way.

let result = condition ? value1 : value2;

If condition is truthy, the expression returns value1. Otherwise, it returns value2.


Example: Instead of writing an if-else to set accessAllowed:

let accessAllowed = (age > 18) ? true : false;

The parentheses are optional — ? has low precedence, so the comparison runs first anyway.

The ternary operator is the only JavaScript operator with three operands. It returns a value, it does not execute code.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

Insight Note — when the ternary is unnecessary

The comparison already returns a boolean

In this particular case, the comparison age > 18 already returns true or false, so the ternary is unnecessary. We could just write:

let accessAllowed = age > 18;

The ternary shines when you need to return different values (like strings or numbers), not just true or false.

A common beginner mistake: using the ternary to produce a boolean when the condition already is one.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.5 — Worked example

Example 2.1.6: Ticket Price

Example 2.1.6 — Ticket Price

Use the conditional operator to set a variable price to 10 if a person’s age is under 12, and 15 otherwise.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Since 8 is less than 12, price is set to 10.

A good use of the ternary: picking between two numeric values.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.5 — Practice

Try It Now 2.1.6

Try It Now 2.1.6

Declare a variable isMember set to true. Use the conditional operator to set a variable discount to 20 if isMember is true, and 0 otherwise. Show the result.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Since isMember is true, discount is set to 20.

Another good ternary use: picking a discount rate based on membership status.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.6 — Chaining ternaries

Multiple ‘?’

You can chain multiple ? operators together to return a value from more than two options.

let age = prompt('age?', 18);

let message = (age < 3) ? 'Hi, baby!' :
  (age < 18) ? 'Hello!' :
  (age < 100) ? 'Greetings!' :
  'What an unusual age!';

console.log(message);

JavaScript evaluates from left to right and returns the first matching value.

Chained ternaries are a compact alternative to else-if chains when you only need to pick a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.6 — Worked example

Example 2.1.7: Size Label

Example 2.1.7 — Size Label

Use chained ? operators to set a variable size based on a numeric waist: Under 30: "Small", Under 36: "Medium", Under 42: "Large", Otherwise: "Extra Large".

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Since 34 is less than 36 but not less than 30, size is "Medium".

Chained ternaries work well for mapping numeric ranges to labels.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.6 — Practice

Try It Now 2.1.7

Try It Now 2.1.7

Declare a variable speed set to 55. Use chained ? operators to set a variable zone: Under 25: "School zone", Under 45: "City", Under 65: "Highway", Otherwise: "Autobahn".

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Since 55 is less than 65 but not less than 45, zone is "Highway".

Speed zones are a natural mapping for chained ternaries.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.7 — A common misuse

Non-traditional Use of ‘?’

The ? operator is designed to return a value. Some programmers use it as a shorter replacement for if — but this is not recommended.

Avoid: using ? to run code

(company == 'Netscape') ?
  console.log('Right!') : console.log('Wrong.');

Prefer: using if to run code

if (company == 'Netscape') {
  console.log('Right!');
} else {
  console.log('Wrong.');
}

Our eyes scan code vertically. Code blocks that span several lines are easier to understand than a long, horizontal instruction set.

The ternary is an expression, not a statement. Using it to execute code instead of returning a value is a style violation.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

Insight Note — the rule of thumb

When to use which

Use ? when you need to pick a value. Use if when you need to run different blocks of code. That is the rule of thumb.

Good ternary use (picking a value)

let greeting = (hour < 12)
  ? "Good morning"
  : "Good afternoon";

Good if use (running code)

if (hour < 12) {
  console.log("Good morning");
} else {
  console.log("Good afternoon");
}
The same logic expressed two ways. The ternary is shorter; the if is more readable for complex blocks.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.7 — Worked example

Example 2.1.8: When to Use Which

Example 2.1.8 — When to Use Which

Rewrite this ternary as an if...else statement:

let greeting = (hour < 12) ? "Good morning" : "Good afternoon";
Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Both versions produce the same result. The if...else version is easier to read when the logic grows.

The ternary is fine for simple value assignment. When the logic gets complex, if-else is clearer.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.7 — Practice

Try It Now 2.1.8

Try It Now 2.1.8

The following code uses ? in a non-recommended way. Rewrite it using if...else.

let loggedIn = prompt("Are you logged in? (yes/no)", "");
(loggedIn == "yes")
  ? console.log("Welcome back!")
  : console.log("Please log in.");
Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Both versions work the same way, but the if...else version is easier to read because the two branches are on separate lines.

This is the classic misuse: using the ternary to call functions instead of returning a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.8

2.1.8 Combining Conditions: &&, ||, !

Every condition so far has asked one question. Real programs ask several at once. A game checks that the player is alive and the jump key is down. A door opens when the visitor is not on the blocked list.

This is the classic misuse: using the ternary to call functions instead of returning a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.8 — Definition

Definition 2.1.2: Logical Operators

&& (AND) is true only when the expressions on both sides are true.

|| (OR) is true when at least one side is true.

! (NOT) flips a single value: !true is false, and !false is true.

Read && as “and also”, || as “or else”. Ask whether a single item has to satisfy both tests — if it does, you want &&.

Definition 2.1.2: The three logical operators.

This is the classic misuse: using the ternary to call functions instead of returning a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.8 — Worked example

Example 2.1.9: Both conditions must hold

Example 2.1.9 — Both conditions must hold

Declare age as 15 and hasPermission as true. Open an if on age >= 13 && hasPermission that logs "Access granted.", with an else that logs "Access denied."

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Both sides are true, so && is true. Change hasPermission to false and run it again: one false side is enough to make the whole condition false.

This is the classic misuse: using the ternary to call functions instead of returning a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.8 — Worked example

Example 2.1.10: Either condition is enough

Example 2.1.10 — Either condition is enough

Declare day as "Saturday". Open an if on day === "Saturday" || day === "Sunday" that logs "It is the weekend.", with an else logging "It is a weekday."

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Each side is a complete comparison. day === "Saturday" || "Sunday" reads fine in English and is wrong: the second half is just the truthy string "Sunday", so the condition would be true every day of the week — and it never crashes.

This is the classic misuse: using the ternary to call functions instead of returning a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.8 — Worked example

Example 2.1.11: Flipping a condition with !

Example 2.1.11 — Flipping a condition with !

Declare isRaining as false. Open an if on !isRaining that logs "Walk to school.". Then log isRaining and !isRaining, each with a label.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

A comma hands console.log two values and prints them side by side; + would glue them. And ! does not change the variable — isRaining is still false afterwards.

This is the classic misuse: using the ternary to call functions instead of returning a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.8 — Worked example

Example 2.1.12: A Condition That Is Always True

Example 2.1.12 — A Condition That Is Always True

In mathematics you would write “x is between 0 and 10” as 0 < x < 10. JavaScript accepts that line without complaint, and gets it wrong every time. Log it for x = 500, then for x = -7.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Both are true, and neither number is between 0 and 10. JavaScript works out 0 < x first, then compares that boolean against 10 — so the second step is 1 < 10 or 0 < 10. It never looked at x twice.

This is the classic misuse: using the ternary to call functions instead of returning a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.8 — Practice

Try It Now 2.1.9

Try It Now 2.1.9

Write a condition that prints "Ticket is free" when a person is either under 5 or 65 and over, and "Ticket costs money" otherwise. Test it with an age of 70.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

Either side being true is enough, so this is ||. Try 30 for the other branch, and try 5 and 65 to check the boundaries behave the way you expect.

This is the classic misuse: using the ternary to call functions instead of returning a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1.8 — Practice

Try It Now 2.1.10

Try It Now 2.1.10

The code below is meant to let a player through only when they are alive and have a key. Find the bug and fix it.

Editor
runs in your browser
▶ Press Run to see the output…
Solution
▶ Press Run to see the output…

It used || where the requirement says “and”, so being alive alone opened the door. Now it prints The door stays shut. — correct, the player has no key. Note the broken version ran perfectly happily.

This is the classic misuse: using the ternary to call functions instead of returning a value.
2.1 Conditionals · bookSHelf Programming Concepts§2.1

Glossary — terms introduced in this section

Key Terms

Conditional statement

A programming construct that runs different code depending on whether a condition is true or false.

if statement

Runs a block of code only if a condition is truthy.

else clause

Runs a block of code when the if condition is falsy.

else if

Adds another condition to check when the previous condition was falsy.

Truthy / Falsy

A value that becomes true / false when converted to a boolean.

Conditional (ternary) operator ?

Returns one of two values depending on a condition. The only JavaScript operator with three operands.

Key terms glossary: all seven terms from the section in a two-column layout.
2.1
2.1 Conditionals · bookSHelf Programming Concepts§2.1

§2.1 — Conclusions

What to carry forward

The one idea

A conditional statement lets your program make a choice. The if keyword checks a condition; if it is truthy, the block runs. Add else for the fallback, and else if for multiple branches. The ternary ? is a shorthand for picking one of two values.

The common mistake

Using ? to run different blocks of code instead of to return a value. The ternary is an expression — it produces a value. if is a statement — it runs code. Use each for its purpose, and your code will be clearer.

Next: §2.2 Algorithms and Loops — repeating work with while and for. Back to start.

Closing argument in two ruled cards — the core idea under a heavy top rule, the failure case beside it — over a ghost section numeral. The next-step line reveals last.