T0 Learning to learn · Lesson 1
Your first program: running code and reading what it prints
What a program is, how to run one on this page, printing text and sums with console.log, the difference between text and numbers, names for values, and your first three error messages.
- run a piece of code on this page, change it, and read what it prints
- print text and numbers with console.log, and do sums in the order of operations
- tell a string from a number, and say what + does with each
- give a value a name with const or let, and change one made with let
- read a SyntaxError, a ReferenceError and a TypeError, and fix the slip behind each
The back cover
A computer does nothing by itself. Somebody has to tell it what to do, one small step at a time, in words it can follow. A list of such steps is a program, and writing one is far closer to writing a recipe than to doing magic.
These pages are about the very first steps. One line makes the computer print something. Sums are worked out before they are printed. Text and numbers turn out to be different things. A label can hold a value so that it is used again. And when a line confuses the computer, it answers with a short message that says why.
Everything runs right on the page, so each idea can be tried the moment it appears, changed, broken on purpose, and mended again.
Before you start
The story: A lamp that waits
Rain drums on the roof of the print shop on Inkwell Lane. You shake the water from your coat. Old Ilse does not look up from her desk.
On the desk sits a brass lamp with a small glass window and a row of keys. "Every lamp in Brasshaven does what its script tells it," she says. "Most people never learn to write one. You will start tonight."
She slides the lamp towards you. Its window is blank. "Make it say something," she says. "Anything at all. But it must be exactly what you meant." You look at the keys, and you have no idea where to begin.
This is the first lesson of the Tech School. You need no knowledge of code to begin. You need only a few ideas you already use every day. Each one is listed below with a tiny example, because every one of them comes back in this lesson.
Read the list slowly. If an idea feels new, stop and think about the example until it feels ordinary. Then move on.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| Steps happen in order. A recipe is a list of steps, done from the top down. | Boil water, add tea leaves, add milk, add sugar. Add the milk first and you get a different chai. | A program runs its lines from the top down, one at a time. |
| Exact words matter. One wrong letter can break a thing that needs to be exact. | A UPI ID such as asha@okbank with one letter changed sends no money, or sends it to someone else. | The computer reads every letter of your code exactly. It never guesses what you meant. |
| Brackets come in pairs. An opening bracket needs a closing one. | 2 × (3 + 4) is 14. Remove the closing bracket and the sum stops making sense. | Every ( in code needs its ). A missing one is the most common slip of all. |
| Multiplication comes before addition. This is the order of operations from school maths. | 40 + 55 × 2 is 40 + 110, which is 150, not 190. | Code follows the same order. Brackets change it, just as in maths. |
| Quotation marks show exact words. | She said "chalo". The quotes show the very word she used. | In code, quotes mark a piece of text that must be kept exactly as written. |
| Some numbers are labels, not amounts. | A PIN code such as 411001 or a phone number is never added or multiplied. A price such as 40 rupees is. | Code has two different kinds of value for these: text and numbers. |
| A calculator shows a result only after you press =. | Type 3 × 40 and nothing happens until you press =, then it shows 120. | Code shows a result only when you ask it to print one. |
| Decimals. | 0.5 is a half; 3.5 is three and a half. | Division in code can give decimals, such as 7 / 2 giving 3.5. |
| A label on a jar names what is inside. | A jar labelled Sugar holds sugar. You say "pass the sugar", not "pass the third jar from the left". | Code gives names to values, so you can use them again by name. |
| A remainder is what is left over. | Share 7 laddoos between 2 children: each gets 3, and 1 is left over. | Code has an operator that gives the remainder directly. |
By the end of this lesson you will be able to:
- run a piece of code on this page, change it, and read what it prints;
- print text and numbers with
console.log, and do sums with it; - tell a piece of text (a string) from a number, and say what
+does with each; - give a value a name with
constandlet, and change a value kept withlet; - read the three most common error messages, find the slip behind each, and fix it.
Every code example on these pages runs. Each one was run before it was published, and the output shown under it is the output it really gives. You can press Run on any of them and see the same thing yourself.
In one line
You already know everything this lesson needs: steps in order, exact words, pairs of brackets, the order of operations, and names for things.
What a program is
At a glance
A program is a list of instructions for a computer, written down in advance. The computer follows the list from the top, one line at a time, exactly as written. It never skips a line, never guesses, and never gets bored, even after a billion lines. Each complete instruction is called a statement.
Programs are written in a programming language. The one used here is JavaScript, the language that runs inside every web browser. Its most useful first instruction is console.log, which shows a line of output: the words or numbers placed inside its brackets. Programs run phones, trains, banks and games, and every one of them is such a list.
Take a guess: When an instruction is a silly one, like two spoons of salt in the tea, does the computer notice?
Picture a new cook in a busy dhaba. The owner hands over a recipe card. The cook follows it exactly, line by line, from the top. The cook never skips a line and never guesses. If a line says "add 2 spoons of salt", in go 2 spoons, even if the line was a mistake.
Now picture a cook who is like that, but who can follow a billion lines in a second. That cook is a computer. It is very fast, and it does exactly what the lines say, nothing more and nothing less.
A list of instructions written in a language that a computer can follow. The computer carries them out in order, from the top down.
Each single instruction in a program is called a statement. A statement is like one line of the recipe card: one thing to do.
The language we start with is JavaScript. It is the language of the web. Every web browser can run it: Chrome, Edge, Firefox and Safari, on a laptop or on a phone. A program called Node.js runs the same language outside the browser, on servers and on your own laptop. So one language takes you a very long way.
Your first line of code
Here is a complete program. It has one statement. Below it is the box that shows what it printed.
console.log("Namaste, Study Room!");
Namaste, Study Room!
Read it aloud, piece by piece, the way you would read a new word slowly:
| Piece | Read it as | What it means |
|---|---|---|
console | console | the console: a window where a program can print messages |
. | dot | "the thing on the right belongs to the thing on the left" |
log | log | the job of writing one line into the console, as a ship's log records each event |
( | open bracket | here come the things to print |
"Namaste, Study Room!" | the text Namaste, Study Room! | the exact words to print; the quotes mark where the text starts and ends |
) | close bracket | that is all there is to print |
; | semicolon | the end of the statement, like a full stop at the end of a sentence |
So the whole line says: console, write this line: Namaste, Study Room!
Look at the output box. The quotes are not printed. They were only there to show where the text begins and ends. The computer printed what was between them, letter for letter.
The three buttons under each block
Run runs the code here on the page and shows what it printed. Edit turns the code into a box you can type in; change anything, then press Run again. Reset puts the code back as it was. Nothing you do can break the page, so try things freely.
You may wonder why it is called "console.log" and not "print". Long ago, a console was the desk of switches and lights where engineers watched a big computer. Today it means the message window that developers keep open. In Chrome you can open it on any web page with the F12 key, then the Console tab. In Node.js the console is the terminal window. The name stayed, and every JavaScript developer types console.log many times a day.
Lines run from the top down
A program with several statements runs them one after another, from the first line to the last. Each console.log prints its own line, in the order the statements are written.
console.log("Boil one cup of water.");
console.log("Add one spoon of tea leaves.");
console.log("Add half a cup of milk.");
console.log("Add sugar, boil, and strain.");
Boil one cup of water.
Add one spoon of tea leaves.
Add half a cup of milk.
Add sugar, boil, and strain.
Why does the order matter so much? Because the computer has no idea what the steps mean. It does not know that milk goes in after the water. It only knows the order you gave it. If you write the lines in another order, it prints them in that order, without a word of complaint.
Worked example 1
Print a three-line greeting card: the first line says Happy Diwali, the second line says From Asha, and the third line says Have a sweet year.
What we have: the three lines of text, in order
What we need: a program that prints them in that order
The plan: one console.log for each line, written in the same order as the card
- Each line of the card is one piece of text, so each goes inside quotes.
- Each piece needs its own
console.log, because eachconsole.logprints exactly one line.
console.log("Happy Diwali");
console.log("From Asha");
console.log("Have a sweet year");
Happy Diwali
From Asha
Have a sweet year
- The output has three lines, in the order of the statements.
Three statements, one per line of the card, in the card's order.
Check: count the lines of output (3) and the statements (3): they match, and each output line is the text inside one pair of quotes.
Worked example 2
A friend wrote the program below and says it prints the steps of a train journey in the wrong order. Predict the output, then fix the program so that it prints Buy the ticket, Reach the station, Board the train.
What we have: a program whose statements are in a muddled order
What we need: the same statements in the order of the journey
The plan: read the program from the top down, writing each output line as you go; then move the statements
- The computer prints in the order of the statements, so first read the program as it is:
console.log("Board the train");
console.log("Buy the ticket");
console.log("Reach the station");
Board the train
Buy the ticket
Reach the station
- The journey's real order is ticket, station, train, so the statements must be moved into that order.
console.log("Buy the ticket");
console.log("Reach the station");
console.log("Board the train");
Buy the ticket
Reach the station
Board the train
Move the statements, not the text inside them: the fixed program prints Buy the ticket, Reach the station, Board the train.
Check: the output now reads in the order a traveller does things.
A path that fails: changing the words inside the quotes instead. The lines would still come out in the program's order, because the computer never reorders anything on its own.
About the semicolon
JavaScript can add a missing semicolon at the end of a line by itself in most cases, so code without them often still runs. In a few cases its guess is not what you meant. This school writes the semicolon every time, so you never have to wonder.
When you are stuck: nothing happens, or nothing is printed
First check that you pressed Run on the right block.
Then check the spelling: console.log in small letters, with a dot in the middle.
Then check the pairs: every ( has its ) and every opening quote has its closing quote.
If the box shows a red message instead of your text, that is an error message. The last section of this lesson teaches you to read it.
Your turn
Change the first program so that it prints your own name instead of Study Room. What do you change, and what stays?Tap to reveal
- Press Edit on the first code block.
- Change only the words between the quotes, for example to
"Namaste, Rohan!". - Press Run.
Only the text inside the quotes changes; console.log, the brackets, the quotes and the semicolon stay as they are.
console.log("One");
console.log("Two");
console.log("Three");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
One
Two
Three
- The program has three statements.
- They run from the top down, and each prints one line.
It prints One, Two and Three, each on its own line, in that order.
How many statements does a program need to print five lines?Tap to reveal
- Each
console.logprints exactly one line (a later lesson shows how one call can print several).
Five, one for each line.
Did you know?
A program written before any computer existed
Long before electricity ran any computer, Charles Babbage designed a calculating machine of gears and rods, the Analytical Engine, and never finished building it. Ada Lovelace published a set of Notes about it. They set out, one operation after another, how the machine could solve certain mathematical problems. Nothing existed that could run those steps. Yet they were complete, exact and in order, and the Computer History Museum says she is often called the first programmer.
Why it fits here: Her Notes were a program in the plain sense used here: a list of exact steps, in order, for a machine to follow.
A loom that read holes in cards
Around 1801, Joseph Marie Jacquard built a loom whose pattern was controlled by cards. Holes punched in each card decided which threads were raised for one pass of the shuttle. A chain of cards, read in order, became the whole pattern, so changing the cloth meant changing the cards and not the loom. A silk portrait of Jacquard himself, woven in 1839, needed 24,000 punched cards.
Why it fits here: The cards were a program: instructions prepared in advance and followed in order, one card at a time, like statements from the top down.
Sources: Computer History Museum: 1801, punched cards control Jacquard loom; Wikipedia: Jacquard machine
In one line
A program is a list of statements that run from the top down, and console.log(...) prints whatever is inside its brackets as one line of output.
Printing numbers and doing sums
At a glance
Inside the brackets of console.log, a sum with no quotes around it is worked out first, and only the answer is printed. The signs are the ones from school, with two changes: a star means times and a slash means divide. A percent sign gives the remainder left after a division.
The order of working is the school order too. Multiplying and dividing come before adding and subtracting, and brackets go first of all. Several values separated by commas come out on one line with a space between them. Decimals hold one small surprise, because the computer stores numbers in binary and some fractions do not fit exactly.
Take a guess: What does a computer print for 0.1 + 0.2: exactly 0.3, or something a little odd?
A shopkeeper at a kirana store adds up a bill in her head: 3 packets of biscuits at 10 rupees each, and 2 packets of milk at 28 rupees each. A computer can do the same sum, and it never gets tired or makes a slip in the arithmetic.
Put a sum inside the brackets of console.log, with no quotes around it. The computer works it out first, then prints the answer.
console.log(3 * 10 + 2 * 28);
86
The star * is how code writes the multiplication sign ×. Read the line aloud as "console dot log of 3 times 10 plus 2 times 28". There are no quotes, so this is not text to copy. It is a sum to work out: 30 + 56 is 86.
The operators, read aloud
An operator is a symbol that does something to the values on either side of it. Here are the arithmetic operators. Most look like the ones from school, with two new ones at the end.
| Operator | Read it as | Example | Result |
|---|---|---|---|
+ | plus | 40 + 55 | 95 |
- | minus | 100 - 35 | 65 |
* | times | 3 * 40 | 120 |
/ | divided by | 7 / 2 | 3.5 |
% | remainder after dividing by | 7 % 2 | 1 |
** | to the power of | 2 ** 10 | 1024 |
Why a star and a slash, and not × and ÷? Because the keys for × and ÷ are not on an ordinary keyboard. The star and the slash are, so every programming language uses them.
The % operator is new. It does not mean "per cent" in code. It gives the remainder: what is left over after sharing out equally. Share 7 laddoos between 2 children: each gets 3, and 1 is left. So 7 % 2 is 1. It is useful far more often than you might expect: is a number even? Then its remainder after dividing by 2 is 0.
console.log(7 / 2, 7 % 2, 2 ** 10);
3.5 1 1024
Look at this line closely. There are three sums inside one pair of brackets, separated by commas. console.log works out each one and prints all three on one line, with a single space between them. That is the second way to use console.log: give it several values, separated by commas.
Several values in one line
Commas let you print a label and a number together. The label is text, so it goes in quotes. The sum is a number, so it does not.
console.log("Total:", 40 + 55);
Total: 95
The space between Total: and 95 was not typed by us. console.log puts one space between the values it is given. A common mistake is to add a space inside the quotes as well, as in "Total: ", and then wonder where the double space came from.
The order of operations
Code follows the order of operations from school maths. Powers are worked out first, then multiplication, division and remainder, then addition and subtraction. Brackets change the order, exactly as they do on paper.
console.log(40 + 55 * 2, (40 + 55) * 2);
150 190
In the first sum, 55 * 2 is 110, then 40 + 110 is 150. In the second, the brackets make the addition happen first: 95, then 95 × 2 is 190. Same numbers, different order, different answer.
Worked example 3
Asha scored 78, 85 and 92 in three tests. Print her average mark.
What we have: three marks: 78, 85 and 92
What we need: the average: the total divided by the number of tests
The plan: add the three marks inside brackets, then divide by 3
- The average is (78 + 85 + 92) ÷ 3. The brackets matter: without them, only the 92 would be divided by 3.
console.log((78 + 85 + 92) / 3);
85
- The total is 255, and 255 ÷ 3 is 85.
Her average is 85.
Check: 85 lies between the lowest mark, 78, and the highest, 92, as an average must.
A path that fails: writing 78 + 85 + 92 / 3. Division comes before addition, so this works out 92 ÷ 3 first and adds it to 78 + 85. That gives about 193.67, bigger than every mark: a sure sign that something went wrong.
Worked example 4
A family of 4 books train tickets at 455 rupees each and pays a booking fee of 30 rupees for the whole booking. Print the label Fare: followed by the total.
What we have: 4 tickets at 455 rupees, plus one fee of 30 rupees
What we need: the total, printed after the label Fare:
The plan: multiply first, then add the fee; print the label and the sum separated by a comma
- The total is 4 × 455 + 30. Multiplication comes first, so no brackets are needed.
console.log("Fare:", 4 * 455 + 30);
Fare: 1850
- 4 × 455 is 1820, and 1820 + 30 is 1850.
The program prints Fare: 1850.
Check: work it the other way: 1850 − 30 is 1820, and 1820 ÷ 4 is 455, the price of one ticket.
Another way: put the fee first: 30 + 4 * 455 also gives 1850, because the multiplication still happens first.
Worked example 5
Is 2026 an even number? Use the remainder operator to find out.
What we have: the number 2026
What we need: its remainder after dividing by 2
The plan: an even number leaves remainder 0 when divided by 2; an odd number leaves 1
console.log(2026 % 2, 2027 % 2);
0 1
- 2026 % 2 is 0, so 2026 shares out into pairs exactly. 2027 % 2 is 1, so 2027 is odd.
2026 is even.
Check: 2026 ends in 6, and every number ending in 0, 2, 4, 6 or 8 is even.
A surprise with decimals
Try adding 0.1 and 0.2. You would expect 0.3.
console.log(0.1 + 0.2);
0.30000000000000004
This is not a bug in JavaScript. The computer stores numbers in binary, using only the digits 0 and 1. In binary, 0.1 cannot be written exactly, just as one third cannot be written exactly in decimals: 0.3333 goes on for ever. So the computer keeps a number very close to 0.1, and the tiny difference shows up after adding.
Python, Java and almost every other language give the same answer, because they store decimals the same way. This is why shops and banks count money in paise, as whole numbers: 10 paise plus 20 paise is exactly 30 paise. A later lesson shows how to round numbers for printing.
When you are stuck: a sum gives the wrong answer
Write the sum on paper the way the computer reads it, and do the multiplications first.
If you meant the addition to happen first, put it in brackets.
Check that each operator is the one you meant: * for times, / for divided by, % for the remainder.
If the answer has a long tail of digits, such as 0.30000000000000004, it is the decimal surprise, not a slip of yours.
Your turn
console.log(10 - 4 - 3, 10 - (4 - 3));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
3 9
- Subtraction of equal rank goes from left to right: 10 − 4 is 6, then 6 − 3 is 3.
- The brackets make 4 − 3 happen first, giving 1, then 10 − 1 is 9.
It prints 3 9: the brackets change the answer.
A cricket team scored 4 sixes and 7 fours, and every other run came from running between the wickets: 52 runs. Write one line that prints the total score.Tap to reveal
console.log(4 * 6 + 7 * 4 + 52);
104
- 4 sixes are 24 runs, 7 fours are 28 runs, and 24 + 28 + 52 is 104.
The team scored 104.
What is 17 % 5?Tap to reveal
- 17 shared into fives gives 3 fives, which is 15.
- 17 − 15 leaves 2.
2.
Did you know?
The first hello, world
The best-known first program in the world prints two words: hello, world. Its first known version is in a tutorial that Brian Kernighan wrote in 1972 for a language called B. That program kept the greeting in three small pieces, hell, then o, w, then orld, and printed them one after another. Printing a short line is still how most people test a new language.
Why it fits here: It is the same act as the first line here: one instruction whose whole job is to print a line of output.
Sources: Wikipedia: Hello, World! program; Bell Labs: A Tutorial Introduction to the Language B, by B. W. Kernighan
When a computer was a person
For about three hundred years a computer was a person whose job was to do sums. Katherine Johnson was one at NASA. In 1962 the astronaut John Glenn was about to orbit the Earth, on a path worked out by new electronic machines. The astronauts were wary of putting their lives in the care of those machines. Johnson was called upon to check the work, and the flight went ahead.
Why it fits here: Her job was what console.log does with a sum: exact arithmetic, in a fixed order, with the answer written down.
Sources: NASA: Katherine Johnson biography; Wikipedia: Computer (occupation)
In one line
Without quotes, console.log works out a sum before printing it; it follows the order of operations, brackets change the order, and commas print several values with one space between.
Text and numbers are different kinds of value
At a glance
Every piece of data in a program is a value, and every value has a type, which says what kind of thing it is. Two types come first. A string is text: any run of letters, digits or signs wrapped in quotes. A number is an amount, written with no quotes at all.
The type decides what an operation does. A plus sign between two numbers adds them. A plus sign with text on either side joins the two into one longer piece of text, so 2 and 3 can become 23. Text that holds digits, such as an amount typed into a box, can be turned into a real number before any sum is done.
Take a guess: A PIN code and a price are both made of digits, so why would you never add two PIN codes?
Look at two things written on a parcel: the PIN code 411001 and the price 411. Both are made of digits. But you would never add two PIN codes together, while you add prices all day. One is a label; the other is an amount.
Code keeps the same difference. Every piece of data a program works with is a value, and every value has a type: the kind of thing it is. In this lesson we meet the two most common types.
A piece of text, written between quotes: "Asha", "411001", "Total:". It is called a string because it is a string of characters, one after another, like beads on a thread.
A value you can do arithmetic with, written with no quotes: 40, 3.5, -12.
The quotes decide the type. 5 is a number. "5" is a string that happens to hold the digit 5. To the computer, these are as different as the price 5 and a sign that says 5.
You can ask JavaScript the type of any value with typeof. Read it as "type of".
console.log(typeof 5, typeof "5");
number string
What + does to each type
Here is the most important surprise of this lesson. The + sign does two different jobs. Between two numbers it adds. When either side is a string, it joins the two pieces of text into one.
console.log(5 + 3);
console.log("5" + 3);
console.log("Rs " + 40 * 3);
8
53
Rs 120
Read each line slowly. In the first, both sides are numbers, so 5 + 3 is 8. In the second, the left side is a string, so JavaScript turns the 3 into text and joins: the text 5 followed by the text 3 makes 53. In the third, the multiplication happens first, as always, giving the number 120; then a string is on the left, so the two are joined into Rs 120.
Joining strings has a name: concatenation, from the Latin for "chaining together". You will meet the word in documentation and in error messages.
A common mistake
Thinking that "5" + 3 gives 8. It gives the text 53. The quotes make the 5 a piece of text, and adding to text joins.
The other operators have only one job, arithmetic. So when they meet a string of digits, JavaScript tries to turn it into a number first. This is called type coercion: forcing a value into another type.
console.log("5" - 3, "5" * "2", "abc" * 2);
2 10 NaN
The text 5 minus 3 gives 2, and the text 5 times the text 2 gives 10, because the strings held digits. But the text abc cannot become a number, so the answer is NaN, which stands for "Not a Number". NaN is JavaScript's way of saying "this arithmetic had no sensible answer".
Why does JavaScript do this at all? It was designed in 1995 to be forgiving on web pages, so that small slips would not stop a page from working. The price of that kindness is that a slip can give a wrong answer quietly, instead of a clear error. Knowing the rule protects you.
Turning text into a number on purpose
Values that a person types on a web page, in a form or a search box, always arrive as strings, even when the person typed digits. So turning text into a number is a job you will do often. Number(...) does it: read it as "number of".
console.log(Number("40") + 3, String(40) + 3, Number("forty"));
43 403 NaN
Number("40") is the number 40, so adding 3 gives 43. String(40) goes the other way and makes the text 40, so adding 3 joins and gives 403. And Number("forty") is NaN: the computer cannot read words as digits.
Worked example 6
A shopping site reads the quantity a customer typed, which arrives as the string "2". The price is the number 250. A developer wrote console.log("2" + 250); to print the bill and got a strange answer. What did it print, and how is it fixed?
What we have: the quantity as a string, "2", and the price as a number, 250
What we need: the bill, 2 × 250 = 500
The plan: predict what the developer's line does, then use the right operator and turn the text into a number
- The left side is a string, so + joins instead of adding:
console.log("2" + 250);
2250
- The bill should multiply the quantity by the price, and the quantity should be a number first:
console.log(Number("2") * 250);
500
The faulty line printed 2250; the fixed line prints 500.
Check: 2 items at 250 rupees each cost 500 rupees, which matches.
A path that fails: leaving the + and only adding Number. Number("2") + 250 gives 252: the arithmetic is right, but it is the wrong arithmetic. Two slips were hiding in one line: the wrong type and the wrong operator.
Worked example 7
Print the line Seats left: 12, where 12 is worked out as 40 seats minus 28 booked.
What we have: 40 seats and 28 booked
What we need: the text Seats left: followed by the number 12
The plan: work out 40 − 28 inside the call, and print it after the label, using a comma
console.log("Seats left:", 40 - 28);
Seats left: 12
- The comma keeps the label and the number as two separate values, and
console.logputs a space between them.
It prints Seats left: 12.
Check: 40 − 28 is 12, and the label and number are separated by exactly one space.
Another way: join them into one string with +: "Seats left: " + (40 - 28) gives the same line. Here the brackets matter: without them, the text and 40 would be joined first, and then subtracting 28 from that text gives NaN.
Worked example 8
Which of these values are strings and which are numbers: 10, "10", 10.5, "ten"? Check with typeof.
What we have: four values
What we need: the type of each
The plan: a value in quotes is a string; digits with no quotes make a number
console.log(typeof 10, typeof "10", typeof 10.5, typeof "ten");
number string number string
- A decimal is still the type number. JavaScript has one number type for whole numbers and decimals alike.
10 and 10.5 are numbers; "10" and "ten" are strings.
Check: the quotes alone decide it, and the output agrees with that rule for all four.
One more thing about quotes. JavaScript accepts double quotes and single quotes alike, so "chai" and 'chai' are the same string. That helps when the text holds a quote mark itself: use the other kind outside.
console.log("It's ready", 'He said "hi"');
It's ready He said "hi"
When you are stuck: + gives a strange join instead of a sum
Ask typeof about each side of the +. If either side is a string, + joins.
Turn the text into a number with Number(...) before adding.
If the result is NaN, one of the values could not be read as a number: print it and look at it.
Your turn
console.log("4" + 4, "4" * 4, 4 + 4);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
44 16 8
- "4" + 4: a string on one side, so + joins: 44.
- "4" * 4: * only does arithmetic, so the text 4 becomes the number 4: 16.
- 4 + 4: two numbers: 8.
It prints 44 16 8.
What is typeof "411001", and why?Tap to reveal
- The value is in quotes.
- Quotes make a string, whatever characters are inside.
string, because of the quotes.
Fix console.log("100" + 50); so that it prints 150.Tap to reveal
console.log(Number("100") + 50);
150
Turn the text into a number first: Number("100") + 50 is 150.
Did you know?
A spacecraft lost to two kinds of number
NASA built the Mars Climate Orbiter to study Mars from orbit. It never did. Two pieces of software had to pass numbers to each other. The software on the ground used English units. The software on board worked in metric. Each number looked fine alone, yet it meant something different on the other side. A navigation error followed, and the mission failed.
Why it fits here: A value is more than its digits: its kind decides what it means, as with a string and a number here.
Source: NASA: Mars Climate Orbiter
A number too big for its box
The first Ariane 5 rocket of the European Space Agency failed soon after it left the ground. The inquiry found errors in the software of the system that told the rocket which way it was pointing. One value was held as a 64-bit number, with room for huge amounts. The program converted it into a 16-bit number, a far smaller box. The value did not fit, and the guidance information was lost.
Why it fits here: Turning one kind of value into another is a real step that can go wrong, which is why it is done on purpose here, with Number(...).
Sources: European Space Agency: Ariane 501, presentation of the Inquiry Board report; Wikipedia: Ariane flight V88
In one line
Quotes make a string (text), and no quotes make a number. + adds two numbers but joins when either side is text, so turn text into a number with Number(...) before doing sums.
Giving values names
At a glance
A name is a label stuck on a value, so that the value can be found again without writing it out each time. In JavaScript the word const makes a name whose value never changes after the first line. The word let makes a name that can be given a new value later, like a jar that is emptied and refilled.
The equals sign in such a line does not ask whether two things are equal. It gives an order: the name on the left is set to the value on the right. A name has to be made on a line above the lines that use it, and good names say what they hold.
Take a guess: If a price is written in twenty places and then changes, how many lines should need fixing?
In a kitchen, every jar has a label: Sugar, Salt, Tea. You never say "pass me the third jar from the left". You say "pass the sugar". The label lets you find the same thing again, by name, as often as you like.
Programs do the same. Instead of writing the price 40 again and again, you put it in a labelled jar once, and then use the label.
A name that holds a value, so that you can use the value again by its name. The name is the label; the value is what is in the jar.
const price = 40;
console.log(price);
console.log(price * 3);
40
120
Read the first line aloud as "const price is set to 40". It makes a new variable called price and puts the number 40 in it. From then on, wherever the program says price, the computer uses 40. So price * 3 is 120.
The word const is short for constant: a value that will not change. Once price holds 40, it holds 40 for good.
A common mistake
Reading = as "equals". In code, = is an instruction, not a statement of fact: it means put the value on the right into the name on the left. Read it as "is set to" or "becomes". Checking whether two values are equal uses a different operator, ===, which a later lesson teaches.
let: a jar you can refill
Some values must change as a program runs: the total of a bill grows with every item, the score of a match grows with every ball. For these, use let instead of const. A variable made with let can be given a new value later.
let total = 0;
total = total + 40;
total = total + 55;
console.log(total);
95
Follow it line by line, the way the computer does. total starts at 0. The second line reads "total becomes total plus 40": the computer works out the right side first, 0 + 40, which is 40, and then puts 40 into total. The third line does the same: 40 + 55 is 95, and total becomes 95. Then it is printed.
Notice that the second and third lines have no let. The word let appears only once, when the jar is first made. After that, you only change what is in it.
Why have const at all, if let can do everything? Because const is a promise. When you read a long program and see const, you know that value never changes, so there is one less thing to keep in your head. If any line tries to change it, JavaScript stops with an error, and a slip is caught at once. Good developers use const by default and let only when a value must change.
const rate = 40;
rate = 45;
Uncaught TypeError: Assignment to constant variable.
at line 2
This is our first error message, and it says exactly what happened: an assignment (putting a value into a name with =) was tried on a constant. The last section of this lesson teaches you to read messages like this one.
The rules for names
| Rule | Allowed | Not allowed |
|---|---|---|
Use letters, digits, _ and $. | unitPrice, item_2, $total | unit-price (the hyphen is a minus sign), unit price (no spaces) |
| Do not start with a digit. | seat2 | 2seat |
| Capital letters count: these are two different names. | price and Price | using Price when you made price |
| Do not use the words of the language itself. | total | let, const, for, class |
When a name has several words, JavaScript developers join them and start each new word with a capital: unitPrice, ticketsBooked, studentName. This style is called camelCase, because the capitals stand up like the humps of a camel. Choose names that say what the value is. seatsLeft tells a reader far more than x.
Worked example 9
A tea stall sells cutting chai at 15 rupees a glass. On one morning it sells 48 glasses. Use named values to print the morning's takings with the label Takings:.
What we have: the price, 15 rupees, and the number sold, 48
What we need: the takings, 15 × 48
The plan: keep each fixed value in a const with a clear name, then multiply the names
const pricePerGlass = 15;
const glassesSold = 48;
console.log("Takings:", pricePerGlass * glassesSold);
Takings: 720
- Both values are fixed for this morning, so both are
const. - The names make the sum read like a sentence: price per glass times glasses sold.
It prints Takings: 720.
Check: 15 × 48 = 15 × 50 − 15 × 2 = 750 − 30 = 720.
Worked example 10
In an over of cricket, a batter scores 1, 4, 0, 6, 2 and 1 from the six balls. Keep a running score with let and print it after the over.
What we have: six scores, one per ball
What we need: the total after the over
The plan: start a let at 0, and add each ball's runs to it in turn
let runs = 0;
runs = runs + 1;
runs = runs + 4;
runs = runs + 0;
runs = runs + 6;
runs = runs + 2;
runs = runs + 1;
console.log(runs);
14
- The score changes after every ball, so it must be a
let, not aconst.
The over gave 14 runs.
Check: add the balls on paper: 1 + 4 + 0 + 6 + 2 + 1 = 14.
A path that fails: writing let runs = runs + 1; on every line. Each let tries to make a new jar with the same label, and JavaScript refuses with SyntaxError: Identifier 'runs' has already been declared. Make the jar once; refill it after that.
Worked example 11
A program uses a name before making it. Predict what happens, then fix it.
What we have: a program that prints discount on its first line and makes discount on its second
What we need: the discount printed without an error
The plan: remember that lines run from the top down, so a name must be made above the line that uses it
console.log(discount);
const discount = 50;
Uncaught ReferenceError: Cannot access 'discount' before initialization
at line 1
- The computer reached the first line before
discountwas given its value.constnames cannot be used before their line has run.
const discount = 50;
console.log(discount);
50
Move the line that makes the name above the line that uses it; then it prints 50.
Check: the fixed program follows the top-down order: make the jar, then use it.
When you are stuck: a name does not work
Check the spelling letter by letter, including capitals: Price is not price.
Check that the line which makes the name (with const or let) is above the line which uses it.
If the error says "Assignment to constant variable", the name was made with const and something tried to change it: use let if it really must change.
Your turn
let stock = 20;
stock = stock - 3;
stock = stock - 5;
console.log(stock);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
12
- stock starts at 20.
- It becomes 20 − 3, which is 17.
- Then it becomes 17 − 5, which is 12.
It prints 12.
Which of these are allowed as names: marks2, 2marks, total-marks, totalMarks?Tap to reveal
- A name cannot start with a digit, so
2marksis out. - A hyphen is a minus sign, so
total-markswould be read as total minus marks.
marks2 and totalMarks are allowed.
Should the number of days in a week be a const or a let?Tap to reveal
- It is 7 and it never changes.
A const: const daysInWeek = 7;
Did you know?
The equals sign has an inventor
The equals sign has an inventor and a birthday. The Welsh mathematician Robert Recorde first used it in 1557, in a book called The Whetstone of Witte. Before that, anyone doing sums had to write the words is equal to in full, line after line. Two short strokes took their place, and more than four and a half centuries later they are on every keyboard.
Why it fits here: Recorde's sign states that two sides are equal; in a program the same sign gives an order, is set to, so the difference needs saying.
Sources: Wikipedia: Equals sign; MacTutor History of Mathematics: Robert Recorde
A name for a number that never changes
Some values never change, and people name them once and for all. The best known is the number you get when you divide the distance round any circle by the distance across it. In 1706 the Welsh mathematician William Jones used the Greek letter π for it, in a book based on his teaching notes for beginners. The name stuck, and it has saved the writing of endless digits ever since.
Why it fits here: It is what const does: one fixed value gets one name, and every later line uses the name.
Sources: Wikipedia: Pi; MacTutor History of Mathematics: William Jones
In one line
const name = value; gives a value a name that never changes, and let makes one you can change later. Read = as "is set to", and make a name above the lines that use it.
Reading your first error messages
At a glance
When a line cannot be followed, the computer stops and says so. Its report is called an error message, and it is not a scolding. It names the kind of problem, gives a short detail, and often points to the very word or sign that stopped the work.
Three kinds turn up first. A SyntaxError means a line breaks the grammar of the language, so nothing runs at all. A ReferenceError means a name was used that nobody made. A TypeError means a value was asked to do something its kind cannot do. Reading the kind, then the detail, then finding the named word, turns most errors into a one-line fix.
Take a guess: When a program stops with an error, is the computer broken, or is it helping?
Go back to the cook in the dhaba. The recipe card says "add 2 spoons of tamarind powdr". The cook stops, and says: "I do not know what tamarind powdr is." That is not the cook being difficult. It is the most useful thing the cook could say. It names the exact word that stopped the work.
An error message is the computer doing the same. It is not a telling-off, and it does not mean you are bad at this. Every developer, from the first day to the fortieth year, sees error messages every day. The skill is to read them calmly, because they almost always say exactly what went wrong.
consol.log("hi");
Uncaught ReferenceError: consol is not defined
at line 1
Read the message in three parts.
| Part | Here | What it tells you |
|---|---|---|
| Uncaught | Uncaught | nothing in the program was set up to deal with this problem, so it stopped. A later lesson shows how a program can catch an error and carry on. |
| The kind of error, before the colon | ReferenceError | the family the problem belongs to. Here: a reference, a name, that the computer could not find. |
| The message, after the colon | consol is not defined | the detail: the exact name it could not find, consol. |
| The trace, on the next line | at line 1 | where: the line of your code the computer was running when it stopped. Count the lines of the code block from the top, starting at 1. |
So the message says: on line 1, I met the name consol, and nobody ever made a thing called consol. Compare it letter by letter with what you meant, console, and the missing e jumps out.
The three kinds you will meet first
| Kind | What went wrong | In the kitchen | A typical message |
|---|---|---|---|
| SyntaxError | the code is not written by the rules of the language, so it cannot even be read | the recipe card is torn, and a line stops halfway | missing ) after argument list |
| ReferenceError | a name is used that does not exist, or not yet | the card names an ingredient nobody has heard of | price is not defined |
| TypeError | a value is used in a way its type does not allow | the card says "chop the milk" | console.lg is not a function |
The word syntax means the rules for how the pieces of a language fit together, the grammar of the language. A SyntaxError is a grammar slip: a missing bracket, a missing quote, two values with no comma between them.
console.log("Total" 95);
Uncaught SyntaxError: missing ) after argument list
An argument is a value you hand to console.log inside its brackets. The computer read the text Total, then expected either a comma (another argument) or the closing bracket. It found 95 instead. So it reports that the ) seems to be missing. The real slip is a missing comma, but the message points to the exact place where reading broke down, and that is where to look.
A message points to where reading stopped
A SyntaxError message names what the computer expected at the point it got stuck. The real slip is at that point or just before it. Look there first.
What runs, and what does not
Watch what happens when the slip is on the second of three lines.
console.log("a");
console.lg("b");
console.log("c");
a
Uncaught TypeError: console.lg is not a function
at line 2
The first line ran and printed a. The trace says at line 2, and the second line asked the console to do a job called lg. There is no such job, so the value of console.lg is nothing at all, and nothing cannot be run like a function. That is a TypeError: the wrong kind of value for what was asked. The program stopped there, so c was never printed.
A SyntaxError behaves differently. The computer reads the whole program before running any of it, the way a careful cook reads the whole card first. If the card cannot be read, not even the first line runs.
console.log("a");
console.log("b";
console.log("c");
Uncaught SyntaxError: missing ) after argument list
Nothing was printed, not even a, although the first line is perfect. That is a useful clue: if nothing at all ran, look for a SyntaxError.
The method, every time
- Read the kind of error: SyntaxError, ReferenceError or TypeError. It tells you what sort of slip to look for.
- Read the message to the end, slowly. It usually names a word or a symbol.
- Find that word in your code, on the line the trace names. A SyntaxError has no trace, because nothing ran: look for the word or symbol it names.
- Compare it, letter by letter, with what you meant.
- Change one thing only.
- Run again, and read the new output. A new error is progress: it means the first one is fixed.
Worked example 12
Fix this program, which should print the price of 3 notebooks at 45 rupees each: Console.log(3 * 45);
What we have: a one-line program and its error message
What we need: a program that prints 135
The plan: run it, read the message with the method, and fix the word it names
Console.log(3 * 45);
Uncaught ReferenceError: Console is not defined
at line 1
- The kind is ReferenceError: a name was not found. The message names
Console. - Compare with the right name,
console: the capital C is the slip, because capitals count.
console.log(3 * 45);
135
Write console with a small c; it prints 135.
Check: 3 × 45 is 135.
A path that fails: adding brackets or quotes around 3 * 45. The message did not mention them; it named Console. Fixing things the message did not point to adds new slips.
Worked example 13
Fix this program, which should print Welcome: console.log("Welcome);
What we have: a program with an opening quote and no closing quote
What we need: a program that prints Welcome
The plan: read the kind of error, then check the pairs of quotes and brackets
console.log("Welcome);
Uncaught SyntaxError: Invalid or unexpected token
- SyntaxError, and nothing ran: the code could not be read.
- A token is one piece of code, such as a word, a number, a symbol or a string. The message says one of the pieces is not valid. Check each pair: the bracket opens and closes, but the quote opens before Welcome and never closes, so the string runs on to the end of the line.
console.log("Welcome");
Welcome
Close the quote after Welcome; it prints Welcome.
Check: count the quotes: two, a pair. Count the brackets: one ( and one ), a pair.
Worked example 14
This program should print 2 lines, Marks: 87 and Grade: A, but something is wrong. Fix it.
What we have: a two-line program, with the error shown below
What we need: both lines printed
The plan: read the message; it names a word; find that word
const marks = 87;
console.log("Marks:", mark);
console.log("Grade:", "A");
Uncaught ReferenceError: mark is not defined
at line 2
- ReferenceError: the name
markwas not found. - The variable was made as
marks, with an s. The second line asked formark. To the computer these are two different names.
const marks = 87;
console.log("Marks:", marks);
console.log("Grade:", "A");
Marks: 87
Grade: A
Use the name exactly as it was made, marks; then both lines print: Marks: 87 and Grade: A.
Check: the output has two lines, as the task asked, and the program stopped nowhere.
When you are stuck: an error message makes no sense
Read only the kind first. SyntaxError: look at brackets, quotes and commas. ReferenceError: look at the spelling of names. TypeError: look at what each value is.
Then read the message again and find the one word or symbol it names.
If you still cannot see it, cut the program down: remove lines until the error goes away. The last line you removed holds the slip. Lesson 3 of this track teaches this cutting-down in full.
Copy the exact message into a search engine. Thousands of people have met the same one, and the answers are a search away.
Your turn
console.log("start");
console.log(score);
console.log("end");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
start
Uncaught ReferenceError: score is not defined
at line 2
- The first line runs and prints start.
- The second line uses
score, which was never made: a ReferenceError, and the program stops. - So the third line never runs.
It prints start, then the error; end is never printed.
A program prints nothing at all and shows an error. Which kind of error is most likely, and why?Tap to reveal
- If even the first line did not run, the computer could not read the program.
- Only a SyntaxError stops everything before the first line runs.
A SyntaxError.
What is the slip in console.log("Price", 40 "rupees");?Tap to reveal
- Between the values 40 and "rupees" there is no comma.
- Every value after the first needs a comma before it.
A missing comma before "rupees".
Did you know?
The bug that was a real moth
A fault in a program is called a bug, and one famous bug was a real insect. Around 1947, operators of an early computer at Harvard traced a problem to a moth caught in the machine. They taped the dead moth into the logbook for the computer. The Computer History Museum marks 9 September as the day of the first actual computer bug being found.
Why it fits here: The operators did what is taught here: they found the exact thing that stopped the work, wrote it down, and fixed that one thing.
Sources: Computer History Museum: September 9, first instance of actual computer bug being found; Wikipedia: Bug (engineering)
Paid for every error found
Donald Knuth writes famous books about programming, and he still expects mistakes in them. So he pays for them. The first person to report a real error is entitled to a reward of at least 2 dollars and 56 cents. The odd sum is 256 cents, which he calls one hexadecimal dollar: a dollar counted in sixteens, the way computers like to count.
Why it fits here: Even an expert's work holds errors; what matters is the habit taught here: read the report, find the exact slip, fix it.
Sources: Donald Knuth's own page: The Art of Computer Programming and other books; Wikipedia: Knuth reward check
In one line
An error message gives the kind (SyntaxError, ReferenceError, TypeError) and the detail; read both, find the word or symbol it names, fix one thing, and run again.
Where it is used
Everything in this lesson is used by working developers every day. Here is where each piece shows up in real work.
| What you learned | Where it is used | A real example |
|---|---|---|
console.log | finding out what a program is really doing, step by step | a developer at a food delivery app prints the bill at each step to find where an extra 20 rupees crept in |
console.log in the browser | the Console tab of Chrome's developer tools (F12) | checking what a web page's own code prints while you click its buttons |
console.log in Node.js | the terminal, and the logs of servers | a booking server writes a line for every ticket sold, and the logs are searched when something goes wrong |
console.log in an extension | the service worker's console of a Chrome extension (the browser extensions step) | printing each message an extension receives, to see why a button does nothing |
| arithmetic operators | bills, scores, statistics, page layouts, games | a results portal works out each student's percentage: total marks ÷ maximum marks × 100 |
%, the remainder | even or odd, every n-th item, time on a clock | striping every second row of a table grey; turning 135 minutes into 2 hours and 15 minutes |
strings and Number(...) | everything a person types into a web form | a quantity box gives the text "2"; the cart must turn it into the number 2 before multiplying |
const and let | every JavaScript program ever written | a tax rate kept in a const; a cart total kept in a let that grows with each item |
| reading error messages | every day of every developer's life | a deploy fails with "ReferenceError: API_KEY is not defined": the message names the missing setting |
The Where-used atlas collects tables like this one for the whole school: which loop, which join, which sort to use, and where each is used in real systems. It grows with every track.
Mistakes and debugging
These are the slips that beginners meet most often, with the message each one gives and the fix. Every message below is the real one, from the code shown.
1. Curly quotes from a phone or a word processor
WhatsApp, Word and Google Docs turn straight quotes into curly ones: “like these”. JavaScript accepts only the straight quotes from the keyboard. Code copied from a chat often breaks for this reason alone.
console.log(“Hello”);
Uncaught SyntaxError: Invalid or unexpected token
The fix: retype the quotes with the keyboard's own key, or copy code only from a code editor or a code block like the ones here.
2. A capital letter in the wrong place
Console.log("Hello");
Uncaught ReferenceError: Console is not defined
at line 1
The fix: console is all small letters. JavaScript treats capitals as different letters, everywhere: in its own words and in your names.
3. A bracket or a quote that never closes
console.log("Hello";
Uncaught SyntaxError: missing ) after argument list
The fix: count the pairs. Many code editors colour the matching bracket when the cursor touches one, which makes a missing partner easy to spot.
4. Two values with no comma between them
console.log("Total" 95);
Uncaught SyntaxError: missing ) after argument list
The fix: put a comma between the values: console.log("Total", 95);. The message talks about a ) because the computer, finding no comma, expected the list to end there.
5. Text where a number was needed
console.log("10" + 5);
105
No error at all, which makes this the most dangerous slip on the list: the program runs and gives a wrong answer quietly. The fix: Number("10") + 5 gives 15. When a sum looks strange, ask typeof about each value.
6. Using a name before it is made, or spelling it differently
const total = 95;
console.log(Total);
Uncaught ReferenceError: Total is not defined
at line 2
The fix: use exactly the name you made, with the same capitals, and make it above the line that uses it.
7. Changing a const
const seats = 40;
seats = seats - 1;
Uncaught TypeError: Assignment to constant variable.
at line 2
The fix: if the value must change, make it with let. If it should not change, the error has caught a real slip: find out why the program tried to change it.
The debugging corner: print to see
When a program gives a wrong answer and no error, put console.log lines in to see each value on the way. Print the value just before the sum, and just after. The first place where a printed value is not what you expected is where the slip is. This one habit finds a great many bugs, and the next lessons of this track build on it.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
// print one value, or several with commas (one space between them)
console.log("Namaste");
console.log("Total:", 40 + 55);
// operators: + - * / % (remainder) ** (power); brackets first, then * / %, then + -
console.log((40 + 55) * 2, 7 % 2, 2 ** 3);
// strings are text in quotes; + joins text; Number(...) turns text into a number
console.log("5" + 3, Number("5") + 3, typeof "5");
// const: a name that never changes; let: a name you can change
const price = 40;
let total = 0;
total = total + price;
console.log(total);
Namaste
Total: 95
190 1 8
53 8 string
40
| When you see | It means | Look at |
|---|---|---|
| SyntaxError | the code cannot be read; nothing ran | brackets, quotes, commas |
| ReferenceError: x is not defined | the name x was never made, or is spelt differently | spelling and capitals; the order of lines |
| TypeError: ... is not a function | something that is not a function was run like one | the spelling of the job after the dot |
| TypeError: Assignment to constant variable. | a const was changed | use let, or find why it changed |
| NaN | arithmetic with something that is not a number | print each value and its typeof |
A line that starts with //, as in the card above, is a comment: a note for people. The computer skips it. Comments explain why the code does what it does.
The story: The first words
The lamp's window glows, and your words appear, letter for letter: the line you typed, and nothing else. You try a number, then a sum, and the lamp answers each one.
Corin, leaning in the doorway, laughs. "I made mine print my name backwards once. By accident." Ilse dips her pen and writes your name in the apprentices' book, under a long list of names. "One lamp," she says. "The city has forty thousand. Come back tomorrow."
You walk home in the rain, and every lamp you pass looks different now.
Reagents gathered: program, string, number, variable, console.log.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- The ECMAScript language specification (ECMA-262) (Ecma International copyright; facts and ideas only)
- The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)