if
Colan Biemer
let score = 45; console.log("You passed!");
Every program so far runs every line, from top to bottom, so a 45 still passes. How can a program decide what to do?
A program makes decisions by asking yes-or-no questions. Is the order at least $50? Did the user leave the password box empty?
The answer is a boolean: true or false. A variable can hold it, like any other value:
true
false
let total = 60; let freeShipping = total >= 50; // true
===
5 === 5
!==
5 !== 5
<
3 < 5
>
3 > 5
<=
5 <= 5
>=
4 >= 5
A comparison always gives a boolean.
= is already taken, so why three equals signs?
=
= puts a value in a variable. === asks whether two values are equal, and gives back true or false.
let a = 5; let isFive = a === 5; // true
The second line has both: === asked the question, and = put the answer in isFive.
isFive
==
"404" == 404
Source: Allen Wirfs-Brock and Brendan Eich, "JavaScript: The First 20 Years" (2020)
Make these two files in a new WebStorm folder:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Practice</title> </head> <body> <script src="practice.js"></script> </body> </html>
practice.js starts empty. Open the page and its console, and clear practice.js before each problem.
practice.js
let score = 72; // Store whether score is 60 or more in passed, then print it.
Console
let score = 72; let passed = score >= 60; console.log(passed);
>= asks the question, and = stores the answer.
Pseudocode is a plan for a program, written in plain English but laid out like code. Your problems use it.
Pseudocode
set first to "Ada" print first
JavaScript
let first = "Ada"; console.log(first);
Pseudocode drops the let, ;, and ( ). We write the plan first, then turn each line into code.
let
;
( )
set first to "Ada" set second to "Grace" set same to whether first and second are equal print same
let first = "Ada"; let second = "Grace"; let same = first === second; console.log(same);
=== compares strings as well as numbers.
else
let score = 45; let passed = score >= 60; // false console.log("You passed!");
passed holds the right answer, but the last line runs anyway. How do we run a line only when something is true?
passed
if (condition) { // runs only when condition is true }
{ }
}
let score = 45; let warning = ""; if (score < 60) { warning = "Below passing"; }
score
warning
"Below passing"
""
For 80, 80 < 60 was false, so the code inside of the if-statement brackets ({ ... }) was never run.
80 < 60
{ ... }
if (score >= 60) { console.log("Pass"); } if (score < 60) { console.log("Fail"); }
These two checks ask the same question twice. How do we say "otherwise"?
let total = 60; let shipping; if (total >= 50) { shipping = "free"; } else { shipping = "$5"; }
total
shipping
"free"
"$5"
else runs when the condition is false. Exactly one of the two blocks runs, every time.
let number = 7; // Print "even" if number is even. Otherwise, print "odd".
odd
let number = 7; if (number % 2 === 0) { console.log("even"); } else { console.log("odd"); }
An even number has a remainder of 0 when divided by 2.
set name to "" if name is empty print "Guest" else print name
Guest
let name = ""; if (name === "") { console.log("Guest"); } else { console.log(name); }
"" is an empty string. We could also test with name.length === 0.
name.length === 0
else if
if (score >= 80) { grade = "A"; } else { grade = "F"; }
if and else give two paths, but a 75 is neither an A nor an F. How do we choose from three?
if (firstCondition) { // runs when firstCondition is true } else if (secondCondition) { // runs when firstCondition is false and secondCondition is true } else { // runs when both are false }
JavaScript checks the conditions from top to bottom. It runs the block under the first true condition and skips the rest. We can add as many else ifs as we need, and the else at the end is optional.
let score = 75; let grade; if (score < 60) { grade = "F"; } else if (score < 80) { grade = "C"; } else { grade = "A"; }
Reaching the else if already means score >= 60, so we don't check it again.
score >= 60
if (score < 80) { grade = "C"; } else if (score < 60) { grade = "F"; } else { grade = "A"; }
We swapped the first two checks from Letter Grades. For a score of 40, 40 < 80 was true, so JavaScript ran the first block and skipped the rest.
40 < 80
Every number that's < 60 is also < 80, so grade can never be "F".
< 60
< 80
grade
"F"
Put the narrowest check first.
let temperature = 75; // Below 50, print "Cold". Below 80, print "Warm". Otherwise, print "Hot".
Warm
let temperature = 75; if (temperature < 50) { console.log("Cold"); } else if (temperature < 80) { console.log("Warm"); } else { console.log("Hot"); }
Reaching the else if already means temperature is 50 or more.
temperature
set number to -4 if number is above 0 print "positive" else if number is below 0 print "negative" else print "zero"
negative
let number = -4; if (number > 0) { console.log("positive"); } else if (number < 0) { console.log("negative"); } else { console.log("zero"); }
The else catches the one number left: 0.
if (score >= 90) { if (absences < 3) { console.log("Honor roll"); } }
Each new rule adds another level, and an else would need to go in both. How do we ask two questions at once?
a && b
a || b
!a
Each side of && and || is a full comparison, like total >= 10, or a boolean.
&&
||
total >= 10
a
b
&& gives true only when both sides are true.
|| gives false only when both sides are false.
!
To get 10% off, a customer has to spend at least $10 and be a member.
let total = 8; let isMember = true; let getsDiscount = total >= 10 && isMember;
isMember
getsDiscount
Say we only care about two letters, a and e.
e
let letter = "a"; let isMatch = letter === "a" || letter === "e";
letter
isMatch
"a"
"e"
"z"
Each side of || needs its own letter ===. For "z", letter === "a" || "e" gives "e", not false, and an if treats that string as true, so every letter would match.
letter ===
letter === "a" || "e"
A student passes when they are not failing.
let isFailing = score < 60; let passed = !isFailing;
isFailing
! flips the boolean right after it, so !isFailing reads as "not failing."
!isFailing
In math class, 13 ≤ age ≤ 19 means "from 13 to 19." In JavaScript, it lets 45 through:
let age = 45; let isTeen = 13 <= age <= 19; // true
Fixed
let isTeen = age >= 13 && age <= 19;
A range takes two comparisons, joined with &&.
let score = 95; let absences = 1; // With a score of 90 or more and under 3 absences, print "Honor roll". // Otherwise, print "Keep going".
Honor roll
let score = 95; let absences = 1; if (score >= 90 && absences < 3) { console.log("Honor roll"); } else { console.log("Keep going"); }
Both rules have to hold, so we join them with &&.
set day to "Sunday" if day is "Saturday" or day is "Sunday" print "Weekend" else print "Weekday"
Weekend
let day = "Sunday"; if (day === "Saturday" || day === "Sunday") { console.log("Weekend"); } else { console.log("Weekday"); }
Each side of || needs its own day ===.
day ===
let result; if (score >= 60) { result = "Pass"; } else { result = "Fail"; }
All of this picks one of two values. Is there a shorter way?
The ternary operator fits an if/else on one line. Ternary means three parts. Use it when both branches only pick a value; otherwise, use if and else.
set score to 72 set result to "Pass" if score is 60 or more, otherwise "Fail" print result
Pass
Use the ternary operator.
let score = 72; let result = score >= 60 ? "Pass" : "Fail"; console.log(result);
Both branches only pick a value, so the ternary fits.
Colan's Coffee is a full page built from today's if statements, with step-by-step instructions.
age >= 13 && age <= 19
condition ? a : b
Objects and Loops groups related values together and repeats code.