Programming Concepts · Chapter 2 · Control Flow
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
Outline — by the end of this section you will be able to
if statement that runs code only when a condition is true ifelse clause to run code when a condition is false elseelse if else if? to pick a value ternaryif vs. the ? operator judgment§2.1.1 — The fundamental decision-maker
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!');
Context Pause — why braces matter
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!");
}
§2.1.1 — Worked example
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!".
▶ Press Run to see the output…
▶ Press Run to see the output…
Since 35 is greater than 30, the condition is true and the message prints.
§2.1.1 — Practice
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.
▶ Press Run to see the output…
▶ Press Run to see the output…
Since 85 is greater than or equal to 70, the condition is true and the message prints.
§2.1.1 — Worked example
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.
▶ Press Run to see the output…
▶ 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.
§2.1.1 — Practice
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.
▶ Press Run to see the output…
▶ 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.
§2.1.2 — How JavaScript decides true or false
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
§2.1.2 — The central idea
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) { ... }
Insight Note — a common beginner pattern
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");
}
§2.1.2 — Worked example
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."
§2.1.2 — Practice
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.
▶ Press Run to see the output…
▶ 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 other side of the branch
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.
§2.1.3 — Worked example
Example 2.1.4 — Even or Odd
Write code that checks whether a number is even. If it is, show "Even". Otherwise, show "Odd".
▶ Press Run to see the output…
▶ 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".
§2.1.3 — Practice
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.
▶ Press Run to see the output…
▶ Press Run to see the output…
Since 16 is less than 18, you see "Too young to vote".
§2.1 — 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.
Pairs with Example 2.1.4.
Figure 2.1.1
§2.1.4 — More than two branches
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.
Context Pause — why order matters
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"); }
§2.1.4 — Worked example
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".
▶ Press Run to see the output…
▶ Press Run to see the output…
Since 85 is greater than or equal to 80 but less than 90, you see "B".
§2.1.4 — Practice
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.
▶ Press Run to see the output…
▶ Press Run to see the output…
Since 14 is less than 18 but not less than 12, you see "Afternoon".
§2.1 — 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.
Pairs with Example 2.1.5.
Figure 2.1.2
§2.1.5 — A shorter way to pick a value
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.
Insight Note — when the ternary is unnecessary
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.
§2.1.5 — Worked example
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.
▶ Press Run to see the output…
▶ Press Run to see the output…
Since 8 is less than 12, price is set to 10.
§2.1.5 — Practice
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.
▶ Press Run to see the output…
▶ Press Run to see the output…
Since isMember is true, discount is set to 20.
§2.1.6 — Chaining ternaries
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.
§2.1.6 — Worked example
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".
▶ Press Run to see the output…
▶ Press Run to see the output…
Since 34 is less than 36 but not less than 30, size is "Medium".
§2.1.6 — Practice
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".
▶ Press Run to see the output…
▶ Press Run to see the output…
Since 55 is less than 65 but not less than 45, zone is "Highway".
§2.1.7 — A common misuse
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.
Insight Note — the rule of thumb
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");
}
§2.1.7 — Worked example
Example 2.1.8 — When to Use Which
Rewrite this ternary as an if...else statement:
let greeting = (hour < 12) ? "Good morning" : "Good afternoon";
▶ Press Run to see the output…
▶ Press Run to see the output…
Both versions produce the same result. The if...else version is easier to read when the logic grows.
§2.1.7 — Practice
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.");
▶ Press Run to see the output…
▶ 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
&&, ||, !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.
§2.1.8 — Definition
&& (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.
§2.1.8 — Worked example
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."
▶ Press Run to see the output…
▶ 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.
§2.1.8 — Worked example
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."
▶ Press Run to see the output…
▶ 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.
§2.1.8 — Worked example
!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.
▶ Press Run to see the output…
▶ 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.
§2.1.8 — Worked example
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.
▶ Press Run to see the output…
▶ 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.
§2.1.8 — Practice
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.
▶ Press Run to see the output…
▶ 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.
§2.1.8 — Practice
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.
▶ Press Run to see the output…
▶ 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.
Glossary — terms introduced in this section
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.
§2.1 — Conclusions
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.
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.