Warm-up · Activity 1 of 7
// B3.1 · ~30 min · Beginner
if, else and truthiness
After this lesson you write if, else if and else chains that pick the right branch, know which values count as false, and use &&, ||, ! and ?? for conditions and defaults.
Lesson 1 of 5 in B3 Control flow and loops
You will be able to
- Write if, else if and else chains with blocks, and predict which branch runs
- Tell the eight falsy values from truthy ones such as "0", [] and {}
- Predict the value that &&, ||, ! and ?? return, and choose || or ?? for a default
Predict · Activity 2 of 7
Predict before you read on: a form field gave you the text "0". What does this print?
const input = "0"; if (input) { console.log("got an answer"); } else { console.log("no answer"); }Practice · Activity 3 of 7
The saved volume 0 is a real setting. Fill in the operator so that the program prints 0, and would use 50 only if nothing were saved (null or undefined).
const saved = 0; const volume = saved ____ 50; console.log(volume);const volume = saved 50;Practice · Activity 4 of 7
It is 25 degrees. What does this print?
const temp = 25; if (temp > 10) { console.log("mild"); } else if (temp > 20) { console.log("warm"); } else { console.log("cold"); }Practice · Activity 5 of 7
Match each expression to the value it gives.
Brain teaser · Activity 6 of 7
Brain teaser. The shopping list is empty. What does this print?
const list = []; if (list) { console.log("time to shop"); } else { console.log("nothing to buy"); }Apply · Activity 7 of 7
Mini-task. Write a cinema till: children under 6 go free, under 18 pay 6 EUR, everyone else 10 EUR. Store the age in a constant and print the price with an if, else if and else chain. Then greet the guest with their nickname, or "movie fan" when the nickname is null. Try the ages 3, 6, 17, 18 and 40.
Check your work against this list
Build it yourself
Read the worked example, then write the exercises. Your code runs in your browser or on your computer and is never uploaded.
Worked example
A delivery checker
This program decides how an order is shipped. An else if chain picks the shipping price, ! turns a false into a true, an empty coupon counts as false, and ??, && and || fill in the remaining lines. Run it, then change total to 60 or 10, set coupon to "SPRING" or note to "ring twice", and predict each line before you run it again.
main.js
// Decide how an order is shipped.
const total = 42.5;
const express = false;
const coupon = "";
const note = null;
if (total >= 50) {
console.log("Shipping: free");
} else if (total >= 20) {
console.log("Shipping: 2.99 EUR");
} else {
console.log("Shipping: 4.99 EUR");
}
if (!express) {
console.log("Delivery: standard");
}
if (coupon) {
console.log("Coupon:", coupon);
} else {
console.log("Coupon: none");
}
console.log("Note:", note ?? "no note");
console.log("Gift wrap:", total > 40 && "offered");
console.log("Label:", coupon || "STANDARD");
Run it with
node main.jsOutput
Shipping: 2.99 EUR
Delivery: standard
Coupon: none
Note: no note
Gift wrap: offered
Label: STANDARD- 42.5 fails total >= 50 and passes total >= 20, so the second block runs and the else is skipped.
- express is false, so !express is true.
- The empty coupon is falsy: the else block runs, and || replaces it with "STANDARD".
- total > 40 is true, so && goes on and returns its second value, "offered".
Change it and run it
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.
Exercises
Exercise 1 of 2
Fix the weather report
The report says 24 degrees is mild and asks for an umbrella on a dry day. Fix the order of the else if chain, so that above 20 degrees it prints It is warm., and fix the second condition, which sets raining instead of reading it. The program should print It is warm. and then No umbrella needed.
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.
Hints
Hint 1
The chain stops at the first true condition. Is 24 > 10 true?
Hint 2
Put the narrower test, temperature > 20, first, and move It is mild. to the else if.
Hint 3
raining = true stores true in raining. To read the value, write if (raining).
Show a solution
One way to solve it. Yours can look different and still pass the checks.
// A weather report for one day.
const temperature = 24;
let raining = false;
if (temperature > 20) {
console.log("It is warm.");
} else if (temperature > 10) {
console.log("It is mild.");
} else {
console.log("It is cold.");
}
if (raining) {
console.log("Take an umbrella.");
} else {
console.log("No umbrella needed.");
}
Run it on your computer
Install ECMAScript 2026 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.
main.js
// A weather report for one day.
const temperature = 24;
let raining = false;
if (temperature > 10) {
console.log("It is mild.");
} else if (temperature > 20) {
console.log("It is warm.");
} else {
console.log("It is cold.");
}
if (raining = true) {
console.log("Take an umbrella.");
} else {
console.log("No umbrella needed.");
}
main.test.js
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {runMain} from './learnrun.js';
const lines = async () => (await runMain()).trimEnd().split('\n');
test('prints two lines', async () => {
const got = await lines();
assert.equal(got.length, 2, `the program printed ${got.length} line(s), expected 2`);
});
test('24 degrees is warm', async () => {
const got = await lines();
assert.equal(got[0], 'It is warm.', `the first line is ${JSON.stringify(got[0])}, expected "It is warm."`);
});
test('a dry day needs no umbrella', async () => {
const got = await lines();
assert.equal(got[1], 'No umbrella needed.', `the second line is ${JSON.stringify(got[1])}, expected "No umbrella needed."`);
});
package.json
{
"type": "module"
}
package.json tells Node.js that the .js files are modules; keep it in the folder.
Run the program:
node main.jsRun the checks (needs learnrun.js in the same folder):
node --testDownload learnrun.jsExercise 2 of 2
Defaults that keep zero
A user saved the volume 0 and an empty name, and no theme. 0 is a real volume and must be kept; an empty name means no name, so it should become Guest. Change the operators so that the program prints volume: 0, then name: Guest, then theme: light. Do not change the saved values.
Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.
The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.
Hints
Hint 1
Run it first: which line is wrong, and is its saved value 0, "" or undefined?
Hint 2
|| replaces every falsy value, 0 included. ?? replaces only null and undefined.
Hint 3
The volume needs ??, the name needs ||. For the theme, both work, because undefined is replaced by either.
Show a solution
One way to solve it. Yours can look different and still pass the checks.
// Settings saved by the user.
const savedVolume = 0;
const savedName = "";
const savedTheme = undefined;
const volume = savedVolume ?? 50;
const name = savedName || "Guest";
const theme = savedTheme ?? "light";
console.log("volume:", volume);
console.log("name:", name);
console.log("theme:", theme);
Run it on your computer
Install ECMAScript 2026 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.
main.js
// Settings saved by the user.
const savedVolume = 0;
const savedName = "";
const savedTheme = undefined;
const volume = savedVolume || 50;
const name = savedName ?? "Guest";
const theme = savedTheme || "light";
console.log("volume:", volume);
console.log("name:", name);
console.log("theme:", theme);
main.test.js
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {runMain} from './learnrun.js';
const lines = async () => (await runMain()).trimEnd().split('\n');
test('keeps the volume 0', async () => {
const got = await lines();
assert.equal(got[0], 'volume: 0', `the first line is ${JSON.stringify(got[0])}, expected "volume: 0"`);
});
test('replaces the empty name with Guest', async () => {
const got = await lines();
assert.equal(got[1], 'name: Guest', `the second line is ${JSON.stringify(got[1])}, expected "name: Guest"`);
});
test('uses the light theme when none is saved', async () => {
const got = await lines();
assert.equal(got[2], 'theme: light', `the third line is ${JSON.stringify(got[2])}, expected "theme: light"`);
});
test('prints exactly three lines', async () => {
const got = await lines();
assert.equal(got.length, 3, `the program printed ${got.length} line(s), expected 3`);
});
package.json
{
"type": "module"
}
package.json tells Node.js that the .js files are modules; keep it in the folder.
Run the program:
node main.jsRun the checks (needs learnrun.js in the same folder):
node --testDownload learnrun.jsCommon mistakes
elseif in one word
const size = 8;
if (size > 10) {
console.log("large");
} elseif (size > 5) {
console.log("medium");
}
What Node.js prints
SyntaxError: Unexpected token '{'Why, and the fix
JavaScript has no elseif keyword: it reads elseif (size > 5) as a call of something named elseif, and then a { cannot follow. Because the file cannot be read, no line runs. Write else if as two words: } else if (size > 5) {.
A condition without parentheses
const size = 8;
if size > 5 {
console.log("big");
}
What Node.js prints
SyntaxError: Unexpected identifier 'size'Why, and the fix
The condition of an if must sit in parentheses: if (size > 5). Without them, JavaScript expects a ( right after if and stops at the name size. Other languages allow the bare form; JavaScript does not.
?? mixed with || without parentheses
const saved = null;
const name = saved || undefined ?? "guest";
console.log(name);
What Node.js prints
SyntaxError: Unexpected token '??'Why, and the fix
JavaScript refuses to guess whether || or ?? should go first, so it does not let you mix them, or ?? with &&, without parentheses. The whole file then fails to load. Add parentheses to say what you mean: (saved || undefined) ?? "guest", or use one operator only.
JavaScript in the browser: your browser’s own engine, in a sandboxed worker. Syntax errors are located with acorn 8.18.0, MIT. Licence and source
Exit ticket
5 questions, no hints. Score 80% or more to complete the lesson.
Finish every activity above to unlock the exit ticket.