2.1 Conditionals

Aligned outcomes:

SLO 2

Describe the principles of structured programming.

Writing if/else chains and ternary expressions teaches the structured-programming principle of selection: every branch has one entry and one exit, and the programmer decides exactly which path runs under which condition.

SLO 4

Explain what an algorithm is and its importance in computer programming.

A conditional statement is a fundamental algorithm building block — it lets the program make decisions based on data, which is what turns a fixed sequence of steps into a general-purpose solution that works for any input.

Learning Objectives

After this section, you will be able to:

In this section, you will learn to:
  • Write an if statement that runs code only when a condition is true.
  • Add an else clause to run code when a condition is false.
  • Chain multiple conditions with else if.
  • Use the conditional (ternary) operator ? to pick a value based on a condition.
  • Decide when to use if vs. the ? operator.
  • Combine several conditions with &&, ||, and !.

2.1.1 The "if" Statement

Sometimes we need our program to make a choice. Should it show one message or a different one? Should it add a discount or not? The if statement is how we tell JavaScript to run some code only when a certain condition is true.

The structure looks like this:

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.

Here is a real example. The program asks the user what year ECMAScript-2015 was published, then checks the answer:

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

If the user types 2015, JavaScript prints the message. Anything else -- nothing happens.

What if we want to do more than one thing when the condition is true? We wrap the block in curly braces:

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

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.

Example 2.1.1: Checking a Number

A program often needs to act only when something is true. Build one step at a time: each comment below is one line for you to write. Press Run when you are done.

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

The message appears because 35 is greater than 30. Change temperature to 20 and run it again -- nothing happens, because the condition is false and the whole block is skipped.

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
Editor
runs in your browser
▶ Press Run to see the output…

You should see Great job! printed because 85 is greater than or equal to 70.

Example 2.1.2: One Equals Sign, or Three?

Look again at the first program in this section. Its condition is year == 2015. Now look at Try It Now 1.2.6, back in Chapter 1, where you compared 100 === 100. Two equals signs in one place, three in another, and one equals sign does something different from both.

Here is the whole rule. There are three of them, not two.

One = stores a value. Two == asks a question, ignoring type. Three === asks a question, including type.

Read them aloud and the difference is hard to lose:

  • let score = 85 is "score gets 85."
  • score == 85 is "is score 85, once you convert?"
  • score === 85 is "is score 85, and a number?"

That is why the first program in this section works. prompt() handed back the string "2015", and year == 2015 converted it to a number before comparing. Switch that one condition to === and the program stops printing anything at all -- Try It Now 2.1.2 takes that apart. Prefer === in your own code: it is the one that cannot surprise you.

The trap is that JavaScript lets you put the storing one inside an if, where you meant to ask the question. Predict what this prints before you run it:

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

It prints Perfect score! -- and then 100.

The condition never asked a question. score = 100 stored 100 in score, and the value it handed back to the if was 100 itself, which is truthy (Section 2.1.2). So the block ran. Worse, the variable was changed on the way past. Set score to 7, or 0, or 999 and run it again: the message appears every single time, because the condition was never a comparison at all.

Change the one = to === and the program finally asks what you meant:

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

Now nothing is printed but 50. The comparison answered false, the block was skipped, and score was left alone.

A condition that is always true is harder to notice than a

program that crashes. Nothing goes wrong on screen -- the message just appears

when it should not. When an if fires every time no matter what you put in

the variable, count the equals signs first.

Try It Now 2.1.2

=== asks whether two values are the same. It also asks whether they are the same type -- a string of digits is not a number, even when it looks like one.

prompt() always hands back a string, even when the user types digits. Predict each line, then run it:

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

The first is true: same type, same value. The second is false, and it is false for a reason worth trusting -- year holds the string "2015", and a string is not a number, however similar the two look printed side by side. typeof confirms it.

So when a comparison surprises you, check the types before you change the comparison. The fix here is to compare like to like: if the value came from prompt(), compare it against a string.

2.1.2 Boolean Conversion

How does JavaScript decide whether a condition is true or false? The if (...) statement evaluates whatever is inside the parentheses and converts it to a boolean -- either true or false.

"Exact" covers one more thing, and it catches people out

more often than the type does: capitalisation. "Yes" === "yes" is

false. So is "Saturday" === "saturday". JavaScript compares two strings

character by character and stops at the first pair that differ, and Y and

y differ. Whenever a condition on text refuses to be true and you cannot see

why, check the capitals before you check anything else — especially when the

text came from somewhere you did not type it yourself, like prompt().

Section 1.2.3's .toLowerCase() is the usual fix: compare

answer.toLowerCase() === "yes" and the capitals stop mattering.

Some values are "falsy" -- they become false when converted:

Every other value is "truthy" -- it becomes 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.

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.

Definition 2.1.1 — 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.

This means the code inside this if will never run:

if (0) { // 0 is falsy
  ...
}

And the code inside this if will always run:

if (1) { // 1 is truthy
  ...
}

We can also store the boolean in a variable first:

let cond = (year == 2015); // equality evaluates to true or false

if (cond) {
  ...
}
Example 2.1.3: Testing Falsy Values

Build it, predict what it shows, then run it -- each comment is one line to write:

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

The empty string "" is falsy, so the condition name is false. The else block runs, and you see "No name entered.".

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
Editor
runs in your browser
▶ Press Run to see the output…

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

2.1.3 The "else" Clause

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

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

If the user types 2015, they see the first message. If they type anything else, they see the second message. Every if that has an else guarantees that exactly one of the two blocks will run.

Example 2.1.4: Even or Odd

The remainder operator % tells you whether a number divides evenly. Build the decision yourself -- each comment is one line to write:

Editor
runs in your browser
▶ Press Run to see the output…
Solution
Editor
runs in your browser
▶ 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 will see "Even". Change num to 7 and run it again to take the other branch.

The else is what makes this a fork rather than a detour. Drawn as a flowchart, an if...else is one diamond with exactly two arrows leaving it, and both of them arrive at the same place.

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 — An if...else is one question with two labelled exits. Whichever branch runs, the program ends up in the same place.

Notice that both arrows out of the diamond reach the End. That is the picture of a closing brace: everything inside the braces belongs to one branch, and the first statement after them belongs to both.

The else is what makes this a fork rather than a detour. Drawn as a flowchart, an if...else is one diamond with exactly two arrows leaving it, and both of them arrive at the same place.

Notice that both arrows out of the diamond reach the End. That is the picture of a closing brace: everything inside the braces belongs to one branch, and the first statement after them belongs to both.

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
Editor
runs in your browser
▶ Press Run to see the output…

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

2.1.4 Several Conditions: "else if"

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

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

JavaScript checks each condition in order:

  1. Is year < 2015? If true, show "Too early..." and stop.
  2. Otherwise, is year > 2015? If true, show "Too late" and stop.
  3. Otherwise, show "Exactly!".

You can have as many else if blocks as you need. The final else is optional -- you can leave it off if you do not need a default case.

The order of conditions matters. JavaScript stops checking as soon as it finds a true condition. Put the most specific conditions first.

Example 2.1.5: Grade Letter

When there are more than two outcomes, else if chains them so exactly one branch runs. Build the chain yourself -- each comment is one line to write. Order matters: the first true condition wins, so the highest cutoff has to come first.

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

Since 85 is greater than or equal to 80 but less than 90, you will see "B". Try moving the score >= 60 branch to the top and running it again -- every passing score becomes a "D", because the chain stops at the first condition that is true.

"The first true condition wins" is hard to see in the code and impossible to miss in a chart. The no exit of each diamond is the only way to reach the next one.

"The first true condition wins" is hard to see in the code and impossible to miss in a chart. The no exit of each diamond is the only way to reach the next one.

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 — An else if chain is a staircase of diamonds. A score only reaches the next question by failing the one above it.

Trace 85 with your finger. It fails >= 90, takes the no arrow, passes >= 80, prints "B", and goes straight to End -- it never reaches the >= 70 diamond at all. Now imagine score >= 60 at the top of the chart and follow 85 again: it stops at the first diamond and prints "D". The chart shows why order matters before you run anything.

Trace 85 with your finger. It fails >= 90, takes the no arrow, passes >= 80, prints "B", and goes straight to End -- it never reaches the >= 70 diamond at all. Now imagine score >= 60 at the top of the chart and follow 85 again: it stops at the first diamond and prints "D". The chart shows why order matters before you run anything.

Try It Now 2.1.5

Declare a variable time set to 14 (representing 2:00 PM in 24-hour format). Write an if...else if...else chain that shows: - "Morning" if time is less than 12 - "Afternoon" if time is less than 18 - "Evening" otherwise

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

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

2.1.5 Conditional Operator '?'

Sometimes we need to assign one of two values to a variable depending on a condition. We could write it with if...else:

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

But JavaScript gives us a shorter way: the conditional operator ?, also called the "question mark" operator or the "ternary" operator. An operand is simply a value an operator works on: a + b gives + two of them, and ? is the only JavaScript operator that takes three.

The syntax:

let result = condition ? value1 : value2;

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

The example above becomes:

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

The parentheses around age > 18 are not strictly required -- the ? operator has low precedence, so the comparison runs first anyway. But parentheses make the intent clearer.

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.

Example 2.1.6: Ticket Price

The conditional operator packs a small if/else into one expression. Build it yourself -- each comment is one line to write:

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

Since 8 is less than 12, price is set to 10. You will see 10 printed. The whole (age < 12) ? 10 : 15 is one expression -- it produces a value, which is why it can sit on the right of an =.

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 with console.log.

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

Since isMember is true, discount is set to 20. You will see 20 printed.

2.1.6 Multiple '?'

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

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

JavaScript evaluates from left to right:

  1. If age < 3, use 'Hi, baby!' and stop.
  2. Otherwise, if age < 18, use 'Hello!' and stop.
  3. Otherwise, if age < 100, use 'Greetings!' and stop.
  4. Otherwise, use 'What an unusual age!'.

The same logic written with if...else:

if (age < 3) {
  message = 'Hi, baby!';
} else if (age < 18) {
  message = 'Hello!';
} else if (age < 100) {
  message = 'Greetings!';
} else {
  message = 'What an unusual age!';
}

Both versions produce the same result. The chained ? version is shorter; the if...else version is easier to read at a glance.

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"

Build the chain yourself -- each comment is one line to write. As with else if, the first true test wins, so the smallest cutoff comes first:

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

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

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"

Show the result with console.log.

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

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

2.1.7 Non-traditional Use of '?'

The ? operator is designed to return a value. Some programmers use it as a shorter replacement for if, like this:

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

This works, but it is not recommended. Here is why: our eyes scan code vertically. Code blocks that span several lines are easier to read than a long horizontal instruction. The if version is clearer:

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

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.

Example 2.1.8: When to Use Which

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

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

This is a good use of the ternary -- it assigns a value to greeting. No rewrite needed. The ternary is the right tool here.

But if the code were doing something more complex, like logging multiple messages or modifying several variables, if...else would be better.

Try It Now 2.1.8

The following code uses ? in a non-recommended way -- it is being used to do two things rather than to produce a value. 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.");

Write your version here:

Editor
runs in your browser
▶ Press Run to see the output…
Solution
Editor
runs in your browser
▶ 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.

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 form accepts an address if the user typed a home address or a work address. A door opens when the visitor is not on the blocked list.

JavaScript has three operators for that, and they are the last piece of conditionals you need.

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"

Beginners mix them up because in everyday speech we say "and" loosely — "give me the students in period 1 and period 2" actually means OR, because no student is in both. When you are unsure, ask whether a single item has to satisfy both tests. If it does, you want &&.

Definition 2.1.2 — && (AND) is true only when the expressions on both sides are true, || (OR) is true when at least one side is true, and ! (NOT) flips a single value.

Example 2.1.9: Both conditions must hold

Each comment is one line to write:

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

What you should see:

Access granted.

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, and the else branch runs.

Example 2.1.10: Either condition is enough

Each comment is one line to write:

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

What you should see:

It is the weekend.

Note that each side is a complete comparison. Writing day === "Saturday" || "Sunday" looks reasonable in English and is wrong in JavaScript: the second half is just the string "Sunday", which is truthy (Section 2.1.2), so the condition would be true on every day of the week.

That mistake is worth dwelling on because it never crashes. The program runs, the branch is simply always taken, and the bug shows up as "the weekend message appears on Tuesday." Each side of && or || has to stand on its own as a question with a yes-or-no answer.

Everyday "or" and || do not always agree. Asked whether

you want fries or salad, you pick one -- English "or" often quietly means "one

or the other, but not both." || never means that. It is true when the left

side is true, when the right side is true, and when both are. When you

translate a sentence into a condition, check whether the English "or" was

hiding a "but not both". If it was, || is not what that sentence meant.

Example 2.1.11: Flipping a condition with !

Each comment is one line to write:

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

What you should see:

Walk to school.
isRaining is false
!isRaining is true

Those last two lines hand console.log two values separated by a comma, rather than joining them with + the way earlier sections did. The comma prints them side by side with a space between. + would glue them into one string instead, so console.log("isRaining is" + isRaining) prints isRaining isfalse, with no space. Either form is fine; the comma just saves you counting spaces.

! does not change the variable — it produces the opposite value for the condition to use. isRaining is still false on the line after.

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, and anyone reading it would know what you meant. JavaScript accepts that line without complaint. It also gets it wrong every time.

Predict what each line prints -- including the one where x is nowhere near between 0 and 10:

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

Both are true. 500 is not between 0 and 10, and neither is -7.

JavaScript reads the line in two steps, left to right. First it works out 0 < x, which is a boolean -- true for 500, false for -7. Then it compares that boolean against 10. To do that it converts the boolean to a number: true becomes 1 and false becomes 0. So the second step is really 1 < 10 or 0 < 10, and both of those are true no matter what x was.

The condition never looked at x twice. Written properly, it has to:

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

Each side of && is a complete comparison naming x -- the same standard the Context Pause above sets for ||.

Try It Now 2.1.9

Write a condition that prints "Ticket is free" when a person is either under 5 years old 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
Editor
runs in your browser
▶ Press Run to see the output…

Output:

Ticket is free

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

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.

const isAlive = true;
const hasKey = false;

if (isAlive || hasKey) {
  console.log("The door opens.");
} else {
  console.log("The door stays shut.");
}

Type it into the editor and run it:

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

It uses || where the requirement says "and". As written, being alive alone opens the door.

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

Now it prints The door stays shut. — correct, because the player has no key. This is the most common logical-operator bug there is, and notice that the broken version still ran perfectly happily.

Problem Set 2.1

2.1.1 Write an if statement that checks if a variable num is positive (greater than 0). If it is, show "Positive".

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

Step 1 — Write the if condition: Use if (num > 0) to check whether num is greater than 0.

Step 2 — Add the action: Inside the block, call console.log("Positive").

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

Answer: The code shows "Positive" when num is greater than 0, and does nothing otherwise.

2.1.2 Write an if...else statement that checks if a variable password equals "secret". If it does, show "Access granted". Otherwise, show "Access denied".

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

Step 1 — Write the condition: Use if (password == "secret") to compare the variable to the string "secret".

Step 2 — Add the if branch: Inside the if block, show "Access granted".

Step 3 — Add the else branch: After the if block, add else with a block that shows "Access denied".

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

Answer: When password is "secret", the code shows "Access granted". For any other value, it shows "Access denied".

2.1.3 Use else if to write a chain that checks a variable temp in Fahrenheit:

  • Below 32: show "Freezing"
  • Below 60: show "Cold"
  • Below 80: show "Warm"
  • Otherwise: show "Hot"
Editor
runs in your browser
▶ Press Run to see the output…
Solution

Step 1 — Check the coldest range first: Start with if (temp < 32) to catch freezing temperatures.

Step 2 — Chain the next ranges: Use else if (temp < 60) for cold, then else if (temp < 80) for warm.

Step 3 — Add the default case: Use else for anything 80 or above.

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

Answer: With temp = 72, the code shows "Warm" because 72 is less than 80 but not less than 60.

2.1.4 Use the conditional operator ? to set a variable fee to 5 if a variable isStudent is true, and 10 otherwise.

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

Step 1 — Write the ternary expression: Use isStudent ? 5 : 10. If isStudent is truthy, the expression returns 5; otherwise it returns 10.

Step 2 — Assign the result: Store the result in fee.

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

Answer: Since isStudent is true, fee is set to 5. The output shows 5.

2.1.5 Use chained ? operators to set a variable rating based on a numeric score:

  • 90 or above: "Excellent"
  • 70 or above: "Good"
  • 50 or above: "Fair"
  • Below 50: "Poor"
Editor
runs in your browser
▶ Press Run to see the output…
Solution

Step 1 — Chain the conditions from highest to lowest: Start with score >= 90, then score >= 70, then score >= 50, and finally the default.

Step 2 — Write the chained ternary:

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

Answer: With score = 85, the first condition (score >= 90) is false, the second (score >= 70) is true, so rating is "Good".

2.1.6 Rewrite the following code using if...else instead of the ? operator:

let result = (a > b) ? "a wins" : "b wins";
Editor
runs in your browser
▶ Press Run to see the output…
Solution

Step 1 — Replace the ternary with an if...else: The ternary checks a > b. If true, it returns "a wins"; otherwise "b wins".

Step 2 — Write the if...else version:

let result;

if (a > b) {
  result = "a wins";
} else {
  result = "b wins";
}

Answer: Both versions produce the same result. The if...else version is longer but easier to read when the logic might grow later.

2.1.7 What is the value of message after this code runs? Explain why. Predict the answer first, then press Run to check it.

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

Step 1 — Evaluate the first condition: age < 1325 < 13false. Move to the next condition.

Step 2 — Evaluate the second condition: age < 2025 < 20false. Move to the next condition.

Step 3 — Evaluate the third condition: age < 6525 < 65true. The expression returns "Adult".

Answer: message is "Adult". Since 25 is less than 65 but not less than 20, the third branch is the first one that matches.

2.1.8 True or false: The values 0, "", null, undefined, and NaN are all truthy.

Solution

Step 1 — Recall the falsy values: JavaScript has exactly six falsy values: false, 0, "" (empty string), null, undefined, and NaN. Every other value is truthy.

Step 2 — Check the list: The problem lists 0, "", null, undefined, and NaN — these are all falsy, not truthy.

Answer: False. All five values listed are falsy, not truthy.

2.1.9 Which condition is true when a number is between 10 and 20, inclusive? a. n >= 10 || n <= 20 b. n >= 10 && n <= 20 c. 10 <= n <= 20

Solution

Step 1 — Understand "between 10 and 20, inclusive": Inclusive means both endpoints count, so the number must satisfy \(n \geq 10\) and \(n \leq 20\) at the same time. Both conditions must hold simultaneously.

Step 2 — Evaluate each option:

  • a. n >= 10 || n <= 20 — This is true if either condition holds. Since every number is either ≥ 10 or ≤ 20 (or both), this is true for all numbers, not just those in range.
  • b. n >= 10 && n <= 20 — Both conditions must be true, which is exactly what "between 10 and 20 inclusive" means. ✓
  • c. 10 <= n <= 20 — JavaScript does not support chained comparisons like math notation. It evaluates left to right: (10 <= n) <= 20, comparing a boolean (true/false) to 20, giving misleading results.

Answer: b. n >= 10 && n <= 20

2.1.10 What does this print?

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

a. true, true, true b. false, true, true c. false, false, true

Solution

Step 1 — Set up the values: loggedIn is true and isAdmin is false.

Step 2 — Evaluate line by line:

$$\texttt{loggedIn \&\& isAdmin} = \texttt{true \&\& false} = \texttt{false}$$

The AND operator requires both operands to be true; since isAdmin is false, the result is false.

$$\texttt{loggedIn || isAdmin} = \texttt{true || false} = \texttt{true}$$

The OR operator needs only one operand to be true; loggedIn is true, so the result is true.

$$\texttt{!isAdmin} = \texttt{!false} = \texttt{true}$$

The NOT operator flips the boolean value.

Answer: b. false, true, true

2.1.11 A shop gives a discount to members who spend at least $50. Which condition is right? a. isMember && total >= 50 b. isMember || total >= 50 c. !isMember && total >= 50

Solution

Step 1 — Identify the requirements: The discount applies when both conditions are met: the customer is a member and their total is at least $50. Requiring two things together means we need the AND operator.

Step 2 — Evaluate each option:

  • a. isMember && total >= 50 — True only when both conditions hold. This matches the shop's rule exactly. ✓
  • b. isMember || total >= 50 — Would give discounts to non-members who spend $50 or to members who spend less than $50, which is wrong.
  • c. !isMember && total >= 50 — Gives discounts only to non-members who spend at least $50 — the opposite of membership.

Answer: a. isMember && total >= 50

2.1.12 Write a condition that prints "Ticket is free" when a person is under 5 or 65 and over, and "Ticket costs money" otherwise.

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

Step 1 — Translate the rule into logic: The ticket is free when the person is under 5 or 65 and over. That's an OR of two conditions: (age < 5) and (age >= 65). Otherwise (the else branch), the ticket costs money.

Step 2 — Write the code:

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

Step 3 — Check the logic against sample ages:

  • age = 3: 3 < 5 is true → free ✓
  • age = 30: both conditions false → costs money ✓
  • age = 70: 70 >= 65 is true → free ✓

Answer: Use if (age < 5 || age >= 65) { console.log("Ticket is free"); } else { console.log("Ticket costs money"); }

2.1.13 This code is meant to open a door only when the player is alive AND has a key. Find the bug and fix it.

const isAlive = true;
const hasKey = false;

if (isAlive || hasKey) {
  console.log("The door opens.");
}
Editor
runs in your browser
▶ Press Run to see the output…
Solution

Step 1 — Read the intended behavior: The door should open only when the player is alive AND has a key. Two required conditions together call for the && operator.

Step 2 — Find the bug: The code uses || instead of &&. With OR, the door opens if either condition is true. Here isAlive is true, so true || false evaluates to true and the door opens even though the player has no key — clearly wrong.

Step 3 — Fix the code:

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

Now true && false is false, so nothing prints and the door stays shut until the player has both conditions satisfied.

Answer: Replace || with &&: the condition should be if (isAlive && hasKey).

2.1.14 Explain why day === "Saturday" || "Sunday" is true on every day of the week.

Solution

Step 1 — Recall how JavaScript evaluates the expression: The expression day === "Saturday" || "Sunday" parses as:

$$(\texttt{day === "Saturday"}) \;||\; (\texttt{"Sunday"})$$

because === binds tighter than ||, so the comparison happens first, then the OR with the string "Sunday".

Step 2 — Apply truthiness: When one operand of || is a non-empty string like "Sunday", that string is truthy (JavaScript treats any non-empty string as true in a boolean context). So the expression becomes:

$$(\texttt{some boolean}) \;||\; \texttt{(truthy value)}$$

If day === "Saturday" is true, the whole expression is true immediately. If it's false, JavaScript returns the second operand, "Sunday", which is truthy — so the expression still acts as true.

Step 3 — Conclusion: No matter what day it is, the expression always evaluates to something truthy. On Monday, for example, day === "Saturday" is false, but false || "Sunday" yields "Sunday", which behaves as true.

Step 4 — The correct fix: Compare day to each string explicitly:

if (day === "Saturday" || day === "Sunday") {
  // weekend
}

Answer: Because "Sunday" is a non-empty (truthy) string, day === "Saturday" || "Sunday" simplifies to (boolean) || "Sunday", which is always truthy regardless of the day. Each side of || must be a full comparison: day === "Saturday" || day === "Sunday".

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.

Loose equality == -- Asks whether two values are equal after converting them to the same type. "2015" == 2015 is true.

Strict equality === -- Asks whether two values are equal and of the same type. "2015" === 2015 is false.

Truthy -- A value that becomes true when converted to a boolean.

Falsy -- A value that becomes false when converted to a boolean.

Conditional (ternary) operator ? -- An operator that returns one of two values depending on a condition. The only JavaScript operator with three operands.

Logical AND && -- True only when the expressions on both sides are true.

Logical OR || -- True when at least one side is true.

Logical NOT ! -- Flips a value: !true is false, !false is true.