Make a program choose which lines run. Ask a condition with if, take the other road with else, ask questions in order with else if, and match one value against exact cases with switch, ending every case with break. See why a box made inside braces is unknown after them, pick one of two values with the conditional operator ? :, and make TaskKit act on its command and answer a missing task with a hint.
TypeScript
Fundamentals
`if` / `else` and `switch`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In the last lesson TaskKit learned to read what you type after node index.ts. Now give it a word it does not know: node index.ts remove "buy milk". It prints Command: remove, then Task: Buy milk, then Tasks added: 1 of 5, room for 4 more. It read your
command and ignored it. Every line in index.ts runs, top to
bottom, whatever you typed, so every command means "add".
Think of a signpost at a fork in the road: Station: turn left.
Everything else: straight on. You read it once, take one road,
and never both. A program can carry a signpost too: a line that
asks a question and, by the answer, runs one group of lines and
skips another. By the end of this lesson TaskKit adds a task only
when you type add, lists its commands on help, names any word
it does not understand, and answers a missing task with a hint
instead of stopping.
if: run some lines only when
Until now a program has had one road: top to bottom, every line.
That is fine for a list of steps, and useless for a question. "Is
the list full?" only matters if the answer can change what
happens next: print a warning when it is full, and say nothing
when it is not.
if asks that question. You write if, then the question,
called a condition, in parentheses, then the lines that depend
on it between curly braces { and }. A condition is any
expression whose value is a boolean, such as the comparisons from
Module 2, added === limit and added < limit, or a method that
answers yes or no, task.includes("milk"). The lines between the
braces are a block: a group of lines that belong together and
run or are skipped as one.
Press Step to watch it line by line:
room.tsts
const limit = 5;let added: number = 5;console.log("Checking the list");if (added === limit) { console.log("The list is full");}console.log("Done");
added === limit is true, so the program goes into the block,
and the output has three lines. Now press Edit, change line 2
to let added: number = 3; and step again. The condition is
false, so line 5 is skipped: the program jumps from line 4 to
the first line after the closing brace and prints only Checking the list and Done.
Three details in that code are not decoration:
The braces decide what the if controls. Everything between
{ and } runs or is skipped together. Line 7 is outside, so it
runs either way.
The lines inside are indented by two spaces. Node ignores
the spaces; people do not. They show at a glance which lines
belong to the block. VS Code (Visual Studio Code, your editor)
indents the next line for you when you press Enter
(return on a Mac) after a {; it may use four spaces
instead of two, and any size works as long as it stays the same
throughout a file.
No semicolon after }. A block ends with its brace.
A condition can also be a box that holds a boolean. Lesson 6 of
Module 2 showed that const full = added === limit; makes a box
of type boolean, and if (full) { asks exactly the same
question. A good name turns the condition into a sentence: if
full.
else: the other road
An if on its own only adds lines when the answer is yes. Often
you want something different when the answer is no: room for more
tasks, or a full list. That is else, written right after
the if block's closing brace, with a block of its own:
room.tsts
const limit = 5;let added: number = 3;if (added < limit) { console.log(`Room for ${limit - added} more`);} else { console.log("The list is full");}
It prints Room for 2 more. Change added to 5 and run it again,
and it prints The list is full. Exactly one of the two blocks
runs, every time: never both, never neither. else has no
condition of its own. It means otherwise, everything the if
did not catch.
Each block a program can take is called a branch: one road at
the signpost. An if with an
else has two branches, and the program takes one of them.
else if: more than two roads
TaskKit needs more than two roads: add adds a task, help lists
the commands, and anything else is a word it does not know. Put
another if straight after an else, and you get else if:
a second question, asked only when the first one was false.
The questions are asked from the top, one at a time. The first one
that is true gets its block run, and every block after it is
skipped, even one whose question would also be true. The else
at the end catches whatever no question matched. Choose the word
TaskKit was given on the tabs, then press Next step to follow
its chain one question at a time, or press Play:
command: string
if command==="add"✓true
if command==="help"–never asked
›prints Added:Buymilkcommand:"add"
›prints Commands:add,helpcommand:"help"
else›prints Unknowncommand:removecommand:string
next line›Tasksadded:0of5
The first question that is true wins; the rest are skipped
All 3 steps shown.Step 1 of 3: command === "add" is trueStep 2 of 3: The block runs: Added: Buy milkStep 3 of 3: The next line: Tasks added: 0 of 5
All 3 steps shown.
command: string
if command==="add"✕false
if command==="help"✓true
›prints Added:Buymilkcommand:"add"
›prints Commands:add,helpcommand:"help"
else›prints Unknowncommand:removecommand:string
next line›Tasksadded:0of5
The first question that is true wins; the rest are skipped
All 4 steps shown.Step 1 of 4: command === "add" is falseStep 2 of 4: command === "help" is trueStep 3 of 4: The block runs: Commands: add, helpStep 4 of 4: The next line: Tasks added: 0 of 5
All 4 steps shown.
command: string
if command==="add"✕false
if command==="help"✕false
›prints Added:Buymilkcommand:"add"
›prints Commands:add,helpcommand:"help"
else›prints Unknowncommand:removecommand:string
next line›Tasksadded:0of5
The first question that is true wins; the rest are skipped
All 4 steps shown.Step 1 of 4: command === "add" is falseStep 2 of 4: command === "help" is falseStep 3 of 4: The block runs: Unknown command: removeStep 4 of 4: The next line: Tasks added: 0 of 5
All 4 steps shown.
Whichever block ran, the program then carries on with the line after
the last closing brace. Each block in the figure also shows the type
command has inside it: in the add block TypeScript knows it can
only be "add"; lesson 5 of this module comes back to this. Here is
the same chain as code, with remove in the box. Run it, then
change the word to add and to help:
Neither question is true, so the else runs and prints Unknown command: remove, and the last line runs as always. The final else
is optional: leave it out, and a word that matches nothing runs no
block at all. The last line stands for the rest of TaskKit, which
counts what was added; this short version adds nothing, so it says
0.
switch: one value, many exact matches
Look at the chain again: command === is written in every
question. When you compare one value against a list of exact
words, switch says it more directly. You name the value
once, then list the matches:
switch (command) { names the value to look at.
case "add": is one exact match, ending in a colon. The
lines under it run when command === "add".
break; leaves the switch. The program carries on after
its closing brace.
default: is the else of a switch: its lines run when no
case matched. Like else, it is optional.
switch compares with ===, so the rules from Module 2 hold:
"Add" does not match "add", and the text "5" never matches the
number 5. Press Next step to follow TaskKit's switch when you
type add, and choose a version on the tabs to see what one missing
break changes:
switch (command)holds"add"
case "add":matchprintsAdded: Buy milkbreak;leaves the switch
case "help":printsCommands: add, helpbreak;
default:printsUnknown command: add
} after the switch
Printed
Added: Buy milk
With add typed, break leaves; without it, the next case runs too
All 4 steps shown.Step 1 of 4: "add" against case "add": matchStep 2 of 4: case "add" runs: Added: Buy milkStep 3 of 4: break leaves the switchStep 4 of 4: After the switch
All 4 steps shown.
switch (command)holds"add"
case "add":matchprintsAdded: Buy milkno break
case "help":fell throughprintsCommands: add, helpbreak;leaves the switch
default:printsUnknown command: add
} after the switch
Printed
Added: Buy milkCommands: add, help
With add typed, break leaves; without it, the next case runs too
All 5 steps shown.Step 1 of 5: "add" against case "add": matchStep 2 of 5: case "add" runs: Added: Buy milkStep 3 of 5: Falls into case "help": Commands: add, helpStep 4 of 5: break leaves the switchStep 5 of 5: After the switch
All 5 steps shown.
A case is a place to jump to, not a block with walls around it.
Once the program has jumped in, it runs every line below, case
labels or not, until a break or the end of the switch. Running
on into the next case like that is called falling through,
and nothing warns you about it.
Bad — the first case has no
break, so add prints the help text as well.
The first version passes the check and runs without a word of
complaint, and every add in TaskKit would answer with the command
list too. End every case with break. Put default last; with
nothing below it to fall into, it needs none.
if or switch?
Both make the same choices; what differs is the kind of question
they can ask. Here is TaskKit's three-way choice written both
ways:
Does: Asks any yes-or-no question: ===, <, includes()
Never: Names the value only once
index.ts
switch (command) { case "add": console.log("Added: Buy milk"); break; case "help": console.log("Commands: add, help"); break; default: console.log("Unknown command:", command);}
switch
Does: Names the value once and lists the exact matches
Never: Asks <, > or any other question than "equal?"
The same choice both ways: switch matches one value exactly
The rule of thumb: when one value is compared with a few exact
values, such as a command, a status or a menu choice, use switch.
For everything else, such as added < limit, a Number.isNaN()
check or a question about a different box in each branch, use if.
When you are unsure, if always works.
TaskKit chooses by its command
Now TaskKit's step for this module: it checks what it was given
and says something useful instead of guessing. Open index.ts in
~/projects/taskkit. Keep the two lines that read
process.argv, delete the six lines marked -, and put the
switch marked + in their place:
index.tsts
const version = "0.1";const divider = "=".repeat(28);console.log(divider);console.log("TaskKit", version);console.log("Your tasks, in your terminal");console.log(divider);const limit = 5;let added: number = 0;const command = process.argv[2];const typedTask = process.argv[3];const tidyTask = typedTask.trim();const newTask = tidyTask.slice(0, 1).toUpperCase() + tidyTask.slice(1);console.log("Command:", command);console.log("Task:", newTask);added = added + 1;switch (command) { case "add": if (process.argv.length < 4) { console.log( `Add what? Try: node index.ts add "buy milk"` ); } else { const tidyTask = typedTask.trim(); const newTask = tidyTask.slice(0, 1).toUpperCase() + tidyTask.slice(1); console.log("Added:", newTask); added = added + 1; } break; case "help": console.log(`Commands: add "task", help`); break; default: console.log(`Unknown command: ${command}`); console.log("Run node index.ts help to see the commands");}const room = limit - added;console.log( `Tasks added: ${added} of ${limit}, room for ${room} more`);// Rounded: without it, a limit of 3 prints 66.66666666666666const percent = Math.round((added / limit) * 100);console.log(`List ${percent}% full`);
Two things in the add case are new. First, it checks that a task
was typed at all: process.argv.length counts the items, the two
paths included, as you predicted in the last lesson, so fewer than
four means no task: node index.ts add gives three items, the two
paths and add, and a task makes four. Second, the tidying moved
inside the else. The last lesson's warning showed trim()
stopping the program when the task is missing; now it only runs once
the if has made sure there is a task to trim. A case can hold an
if, and an if block can hold another: blocks fit inside each
other, and the indentation shows how deep you are.
That is TaskKit's first line of defence: before any code that
could stop the program, two checks decide whether the words typed
get any further. Choose a line on the tabs and press Next
step:
% node index.ts add"buy milk"
Typed
✓passes: Acommanditknows?
✓passes: Ataskafteradd?
Tidyandadd
add
TaskKit printsAdded: Buy milk
Only a known command with a task gets past TaskKit's checks
All 4 steps shown.Step 1 of 4: Typed: add buy milkStep 2 of 4: A command it knows?: yesStep 3 of 4: A task after add?: yesStep 4 of 4: Inside: Added: Buy milk
Only a known command with a task gets past TaskKit's checks
All 4 steps shown.Step 1 of 4: Typed: addStep 2 of 4: A command it knows?: yesStep 3 of 4: A task after add?: noStep 4 of 4: Stopped: Add what? Try: node index.ts add "buy milk"
All 4 steps shown.
% node index.ts remove"buy milk"
Typed
✕fails: Acommanditknows?
not checked yet: Ataskafteradd?
Tidyandadd
remove
TaskKit answersUnknown command: remove
Only a known command with a task gets past TaskKit's checks
All 3 steps shown.Step 1 of 3: Typed: remove buy milkStep 2 of 3: A command it knows?: noStep 3 of 3: Stopped: Unknown command: remove
All 3 steps shown.
Check the file with tsc (short for TypeScript compiler), then
run it the way a person would:
============================TaskKit 0.1Your tasks, in your terminal============================Added: Buy milkTasks added: 1 of 5, room for 4 moreList 20% full
Now forget the task, the run that stopped TaskKit with a
TypeError in the last lesson:
bash
node index.ts add
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Add what? Try: node index.ts add "buy milk"Tasks added: 0 of 5, room for 5 moreList 0% full
And a word TaskKit does not know:
bash
node index.ts remove "buy milk"
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Unknown command: removeRun node index.ts help to see the commandsTasks added: 0 of 5, room for 5 moreList 0% full
node index.ts help prints Commands: add "task", help under
the banner. Run node index.ts with no word at all, and the
default prints Unknown command: undefined. That undefined is
the "nothing here" value from the last lesson's warning, and
lesson 3 of this module is about it.
Predict before you run
The order of the questions in an else if chain is part of the
program. Read this one top to bottom, the way the computer does,
and decide what it prints.
Predict
What does this program print?
ts
const limit = 5;let added: number = 5;if (added > 0) { console.log("Some room used");} else if (added === limit) { console.log("The list is full");} else { console.log("The list is empty");}
The common mistake: a box inside the braces
A block keeps more than its lines to itself. A box made with
const or let inside a block exists only from its line to that
block's closing brace. Outside, the name is unknown.
Common mistake
Using a box after the block that made it
You want one line about the room left, worked out by an if, so
you make the text in each branch and print it at the end:
room.tsts
const limit = 5;let added: number = 5;if (added === limit) { const notice = "The list is full";} else { const notice = `Room for ${limit - added} more`;}console.log(notice);
npx tsc --noEmit room.ts refuses line 8 with TS2304. Each
notice lived only inside its own braces, and by line 8 both are
gone.
Cannot find name 'notice'.
The fix
Make the box before the if, with let, so it lives outside both
blocks, and fill it with the text for the common case, Room for … more. The if refills it only when the list is full:
room.tsts
const limit = 5;let added: number = 5;let notice = `Room for ${limit - added} more`;if (added === limit) { notice = "The list is full";}console.log(notice);
It prints The list is full.
When Cannot find name points at a name you can see in the file,
look at the braces around the line that makes it. If the line that
uses it is outside them, move the box up, above the if, and
refill it inside.
One of two values: ? and :
The fix above has a shorter form, for when each branch only picks a
value. The conditional operator asks a condition and gives back
one of two values: the one after ? when the condition is true,
the one after : when it is false. It is often called the
ternary operator too, since it takes three parts: the condition,
the value for true and the value for false. You will meet it in
other people's code:
room.tsts
const limit = 5;let added: number = 5;const notice = added === limit ? "The list is full" : `Room for ${limit - added} more`;console.log(notice);
It prints The list is full. Read lines 3 and 4 as a question: is the list
full? Then this text, otherwise that one. Only the chosen value is worked
out, so when the list is full, limit - added is skipped. It is not a block
but a single value, so it goes straight into a const, which never needs
refilling. Use it to pick one of two values. When a branch has lines to run,
write an if.
Pass all five tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
As in the last lesson, where a program would read process.argv,
the value it would hold is put straight into a box, with a comment
saying where it came from.
Exercise · Read the code
Which block runs
Someone typed node index.ts Help. What does this program print?
Write a switch on taskStatus that prints Still to do for
"todo", Finished for "done", and Unknown status: with the
word for anything else. With the value below it prints Finished.
Loading the editor…
Exercise · Write the code
Refuse an estimate you cannot read
Someone typed ten instead of 10, so minutes is NaN (not a
number). Make
the program print Not a number: ten when minutes is NaN, and
the With a break: line only when it is a number.
Loading the editor…
Exercise · Write the code
Say how full the list is
Write an if / else if / else chain that prints The list is full when added equals limit, One place left when exactly
one place is left, and Room for 3 more (with the real number)
otherwise. With the values below it should print One place left.
Loading the editor…
Exercise · Predict the result
Count the lines a switch prints
How many lines does this program print?
ts
const command: string = "help";switch (command) { case "add": console.log("Added"); break; case "help": console.log("Commands"); default: console.log("Unknown");}
Recap
Recap · 3 questions
Check yourself
The condition of an if is false. What happens to its block?
Check yourself
const notice is made inside an if block. Where is it usable?
Check yourself
What does break do in a switch?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
if / else and switch
What things are
Word
What it means
Condition
An expression that gives true or false
Block
Lines in { } that run or are skipped together
Branch
One of the roads a program can take
if
Run a block only when its condition is true
else
Run a block when the if did not
else if
Ask another question when the one before was false
switch
Match one value against exact cases
case
One exact match, a place to jump to
break
Leave the switch
default
The lines that run when no case matched
Falling through
Running on into the next case with no break
Conditional operator
? :, one of two values by a condition
Code
Write
To
if (added === limit) {
Ask, and open the block that depends on it
} else {
Open the block for every other answer
} else if (added > 0) {
Ask the next question
if (full) {
Ask a box that holds a boolean
switch (command) {
Name the value to match
case "add":
Mark the lines for one exact value
break;
End a case
default:
Mark the lines for any other value
full ? "Full" : "Room"
Pick one of two values
Rules
Rule
What it means
One road
Exactly one block of a chain runs, or none
First true wins
Later questions are not even asked
Narrow first
Ask === limit before > 0
===, not =
One = in a condition fills the box
Indent the block
The same indent shows which lines belong to it
Box in a block
Exists only up to that block's }
TS2304
A box used after the block that made it
break every case
Except a default you put last
Exact matches
switch compares with ===: capitals count
Typed word : string
Without it, TS2367: the words cannot match
? : or if
? : picks a value; lines to run need an if
Where to go next
You can now make a program choose: run a block only when a condition is true
with if, take the other road with else, ask several questions in order
with else if, match one value against exact words with switch, ending
every case with break, and pick one of two values with ? :. TaskKit acts
on its command and answers a missing task with a hint instead of stopping.
Next is Logical operators, truthy and falsy values. So far
every condition has asked one thing. There you join two questions
into one condition, such as "is there a task, and is the list not
full", and find out what happens when a condition is not a
boolean at all.
Before you move on, add a command of your own to TaskKit: a
case "version": that prints TaskKit 0.1, with its break.
Add it to the help text too, then run node index.ts version
and node index.ts help, and predict both outputs before you
press Enter.