Comments and names: writing code other people can read
Choose names that say what a box holds, join their words in camelCase, and see why TypeScript refuses a name that is one capital off. Rename a box on every line at once with F2, write comments that say why rather than what, comment a line out, leave a note the hover shows, and give TaskKit a clearer name.
TypeScript
Fundamentals
Comments and names: writing code other people can read. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In the last lesson you rested the pointer on every box in TaskKit
and read the type TypeScript gave it. Now read line 2 of index.ts
as if someone else had written it: const line = "=".repeat(28);. A
line of what? A line of code, a line of the output, the line a task
is on? You wrote it at the end of Module 1, and you have to read the
next lines to remember. Picture that a month from now, in a file ten
times longer.
Think of the boxes in a freezer. One says soup, one says
chicken soup, 3 March, and one says nothing at all. All three
keep the food just as cold; only one of them saves you from
thawing it to find out what it is. Names and comments are those
labels for your code. By the end of this lesson you will choose
names that make a line read on its own, rename a box everywhere at
once without breaking anything, and leave a comment where the code
cannot say why.
Names are for people
A name is the label on a box, and you choose it. The computer
does not care what it says. Node never reads the label for its
meaning: it only uses it to find the same box again on a later
line. Call the box p or percent, and the program does exactly
the same thing:
index.ts
const a = 2;const l = 5;const p = Math.round((a / l) * 100);console.log(`List ${p}% full`);
Does: Reads as a sentence: the percent of the limit added
Two programs the computer runs the same; one you can read
So a name is written for whoever reads the code next: a teammate,
someone who wants to help you, or you after a month away. Run the
short version, then press Edit, give the three boxes the names
from the second card, and run it again:
names.tsts
const a = 2;const l = 5;const p = Math.round((a / l) * 100);console.log(`List ${p}% full`);
Both runs print List 40% full. Only the reading changed. A good
name does three things:
It says what the box holds, in the words of the task:
added, limit, percent. If you would have to explain a name
out loud, the explanation is the better name.
It says what it holds, not its type.number1 and text tell you
what hover already tells you, and nothing about the task. Write
the unit when there is one: estimateMinutes says what 25
means; estimate leaves you guessing minutes or hours.
It is as long as it needs to be, no longer. In a short file
with one limit, limit is enough. With a task limit and a
length limit in the same file, each one needs a word in front:
taskLimit, lengthLimit.
What a name can be
A name is made of letters, digits, _ and $, and nothing else. It
cannot start with a digit, so 2ndTask is refused before anything
runs. It cannot be a keyword, a word the language keeps for itself
such as const, let or new, as lesson 2.1 said: const new = "Buy milk"; is refused with 'new' is not allowed as a variable declaration name.
The rule that matters most every day is that a name cannot hold
a space. So a name of several words has to join them somehow.
Here are three ways to write "first task", and what TypeScript
says about each:
index.ts
const firsttask= "Buy milk";
',' expected.
Joined with a space
Never: A space ends the name: task is read as a second one
index.ts
const first-task = "Buy milk";
',' expected.
Joined with a dash
Never: A dash is a minus: first - task is arithmetic
index.ts
constfirstTask = "Buy milk";
No error
Joined with a capital
Does: One name, and a reader still sees two words
Joining the words: only one way is a name
Joining words with a capital at the start of each one after the
first is called camelCase: the capitals stand up in the middle
of the name like the humps of a camel. It is how TypeScript and
JavaScript code names boxes, and TaskKit already uses it:
firstTask, tidySecond. Every name in this course is written
that way.
A name is matched letter for letter
Camel humps come with a price. TypeScript finds a box by comparing
the name you use with every label, one letter at a time, and a
capital N and a small n are two different letters, as "Milk"
and "milk" were in lesson 2.4: taskname is not taskName. You
first met the message this gives in Module 1, when verison had two
letters swapped; the common mistake at the end of this lesson is the
capital-letter version of it.
Renaming a box safely
The same rule decides how you change a name you no longer like.
Every line that uses the box carries its label, so a rename has to
reach all of them. Do it by hand and it is easy to fix the line that
makes the box and forget the lines below. VS Code (Visual Studio
Code, your editor) can do the whole rename for you: put the cursor
on the name, choose Rename Symbol from the menu you get by
right-clicking it (a symbol is VS Code's word for a name in your
code), or press its key, type the new name and press
Enter, and every place that name is used changes with it:
F2
If F2 changes your screen's brightness instead, hold
fn as you press it.
Here is TaskKit's line becoming divider, a name that says what
the row of = signs is for. In the by-hand version TypeScript's
error carries the code TS2304, explained under the figure. Press
Next step to follow it, or let it play, and switch between the
two ways:
You
VSCode
TypeScript
Node
You: F2 → dividerF2→dividerF2→divider
VS Code: 3 lines changed3lineschanged3lineschanged
TypeScript: checked ✓checked✓checked✓
Node: runsrunsruns
Time
You put the cursor on line, press F2, type divider and
press Enter.
Line 2, where the box is made, and lines 3 and 6, which
print it, all say divider now.
Every name used has a box with exactly that label.
The banner prints exactly as before: a new label, the same
program.
One rename, two ways: every line changes, or only one
All 4 steps shown.Step 1 of 4: You: F2 → dividerStep 2 of 4: VS Code: 3 lines changedStep 3 of 4: TypeScript: checked ✓Step 4 of 4: Node: runs
All 4 steps shown.
You
VSCode
TypeScript
Node
You: edit line 2editline2editline2
VS Code: 1 line changed1linechanged1linechanged
TypeScript: Cannot find name 'line'.Cannotfindname'line'.Cannotfindname'line'.
Node: never startsneverstartsneverstarts
Time
You change line to divider on line 2, where the box is
made, and save.
Only line 2 changed. Lines 3 and 6 still print line.
No box is labelled line any more. Lines 3 and 6 are
refused, TS2304, before anything runs.
The check failed, so not one line runs.
One rename, two ways: every line changes, or only one
All 4 steps shown.Step 1 of 4: You: edit line 2Step 2 of 4: VS Code: 1 line changedStep 3 of 4: TypeScript: Cannot find name 'line'.Step 4 of 4: Node: never starts
All 4 steps shown.
Notice what happens when you rename by hand anyway: nothing breaks
quietly. The forgotten lines name a box that no longer exists, and
TypeScript refuses the file, so you fix it before Node runs a line
of it. This time the message has no Did you mean, and its code is
TS2304, TypeScript's code for a name it cannot find and has no
guess for: divider looks nothing like line. The fix is to read
the line it names and use the new name there too.
Comments say why
Lesson 2.3 showed the comment: two slashes, //, and the computer
skips everything from there to the end of the line. TypeScript does
not check a comment and Node does not run one. It is a note for
people, which raises the question of what is worth saying to them.
A good name already says what a box holds, and the code already
says how it is worked out. What neither can say is why the
line is the way it is. That is the comment's job.
Bad — the comment repeats the
line, so it tells the reader nothing new.
ts
const limit = 3;const added = 2;// Work out the percent and round itconst percent = Math.round((added / limit) * 100);console.log(`List ${percent}% full`);
Good — the comment says why the
line is there, which the code cannot.
ts
const limit = 3;const added = 2;// Rounded: without it, a limit of 3 prints 66.66666666666666const percent = Math.round((added / limit) * 100);console.log(`List ${percent}% full`);
Both print List 67% full. The first comment is gone from your
mind as soon as you read the line under it. The second stops the
next person, you included, from deleting Math.round as clutter
and getting a percent with fourteen decimal places.
A comment can also sit at the end of a line, after the code, and
a note of several lines can go between /* and */, where
everything in between is skipped, line breaks included:
comments.tsts
/* TaskKit, version 0.1. Prints a banner, then the tasks added so far. */const version = "0.1"; // raise it whenever TaskKit learns something newconsole.log("TaskKit", version);
Run it: only TaskKit 0.1 is printed. Nothing in either comment
reaches the output.
The same skipping has a second use. Put // in front of a line of
code and it stops running, while it stays on the page where you can
bring it back. This is called commenting out a line. It is how
you see what a program does without a line, when you expect to want
the line back. VS Code does it for the line the cursor is on, or for
every line you select, with Toggle Line Comment; press the keys
again to take the // away:
⌘ Cmd+/
Ctrl+/
Ctrl+/
A note the hover shows
One kind of comment does more. Start it with /**, two stars
instead of one, and put it right above the line that makes a box:
index.tsts
/** The most tasks the list can hold at once */const limit = 5;
Now rest the pointer on limit, anywhere it is used, and VS Code
shows the note under the type, const limit: 5. This is a doc
comment: a note made for the hover, so a reader gets it without
scrolling back to the line that made the box. A comment that starts
// is never shown there. Most boxes need no such note; a value
whose meaning is not in its name, like a limit someone chose for a
reason the code does not show, is worth one.
TaskKit gets a clearer name and a note
Make the two changes from this lesson in index.ts in
~/projects/taskkit. First the rename: put the cursor on line in
line 2, press F2, type divider and press
Enter. Lines 2, 3 and 6 change together. Then add the
comment marked + above the line that makes percent, and save the
file:
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 tidyFirst = " buy milk ".trim();const firstTask = tidyFirst.slice(0, 1).toUpperCase() + tidyFirst.slice(1);console.log("Added:", firstTask);added = added + 1;const tidySecond = "call the dentist ".trim();const secondTask = tidySecond.slice(0, 1).toUpperCase() + tidySecond.slice(1);console.log("Added:", secondTask);added = added + 1;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`);
Check the file with tsc (short for TypeScript compiler), which
npx starts, then run it:
bash
npx tsc --noEmit index.tsnode index.ts
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Buy milkAdded: Call the dentistTasks added: 2 of 5, room for 3 moreList 40% full
The output is exactly what lesson 2.5 printed.
Predict before you run
Comments change what a program prints only by what they switch
off. Decide what this prints before you run it.
Predict
What does this program print?
ts
let added = 0;added = added + 1;// added = added + 1;added = added + 1; // the second taskconsole.log("Tasks added:", added);
The common mistake: one capital different
With camelCase, capitals sit in the middle of names, and in a
hurry your fingers do not always follow them. You make a tidy copy of the
first task, then use it on the next line:
Common mistake
Using a name with one letter in a different case
npx tsc --noEmit index.ts refuses line 3 with TS2552,
TypeScript's code for a name it cannot find but can guess,, before
anything runs:
When the message ends with Did you mean, compare the two names
letter by letter; the difference is usually one capital. To stop it
happening, let VS Code finish the name for you: as you type the
first few letters, it opens a small list of the names that match,
and Tab or Enter writes the one you pick,
capitals and all.
This program should print Room for 3 more, but TypeScript
refuses line 3. Fix the name so it matches the box.
Loading the editor…
Exercise · Fix the error
Name the boxes for a person
This program works, but nobody can tell what t and d are.
Rename them total and done, everywhere they are used, so it
still prints 2 tasks left.
Loading the editor…
Exercise · Read the code
The comment worth keeping
Which comment is worth writing above this line?
ts
const tidyFirst = " buy milk ".trim();
Recap
Recap · 3 questions
Check yourself
What changes when p is renamed percent everywhere?
Check yourself
What is a comment for, when the names are good?
Check yourself
You rename a box on its first line only. What happens?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Comments and names: writing code other people can read
What things are
Word
What it means
Name
The label on a box, chosen for people to read
camelCase
Words joined, each one after the first capitalised
Comment
A note for people that TypeScript and Node skip
Commenting out
Putting // in front of code to switch it off
Doc comment
A /** */ note shown when you hover the name
Rename Symbol
VS Code changing a name on every line at once
Code and keys
Write
To
// note
Leave a note to the end of the line
/* … */
Leave a note over several lines
/** … */
Leave a note above a box that hover shows
F2
Rename the name under the cursor everywhere
Cmd + /
Comment a line out or back in, on a Mac
Ctrl + /
The same on Windows and Linux
Rules
Rule
What it means
Say what it holds
percent, not p; the unit when there is one
Not its type
number1 and text say what hover already says
Allowed
Letters, digits, _ and $; never a digit first
No space, no dash
first task and first-task are refused
Not a keyword
const new = … is refused
Capitals count
taskName and taskname are two names
TS2552
No such name, with a guess: compare the capitals
TS2304
No such name: a rename that missed a line
Why, not what
A comment says what the code cannot
Change both
Update a comment in the edit that changes its line
Where to go next
You can now choose a name that says what a box holds, join its
words in camelCase, read why TypeScript refuses a name that is off
by one capital, rename a box on every line at once with F2, and
leave a comment, or a note for the hover, that says why. TaskKit's
banner has a divider instead of a line, and its percent has
the reason it is rounded written above it.
Next is Your first input: command-line arguments with
process.argv. So far every task TaskKit adds is written into
the code. The next lesson lets you type a command and a task name
in the terminal, and the names you give those new boxes are the
first thing the next reader will look for.
Before you move on, read index.ts from the top as if someone
else had written it. Find one name you would have to explain out
loud, rename it with F2, and check and run the file. Then put the
cursor on one of the console.log(divider); lines, comment it out
with the keys from this lesson, run the file to see the banner
lose a line, and bring it back.