Learn JavaScript

Lesson 1 of 8 · First Programs: The Console, let and const, Types, typeof

Module 1 · First Programs: The Console, let and const, Types, typeof

A Program Line by Line: console.log, Numbers and Text

FreeReading

In this lesson

  • Write a short program that prints text, a number and the result of a sum.
  • Use the six arithmetic operators, and explain why 7 / 2 prints 3.5 and not 3.
  • Read the messages Node 22 prints when a first program is typed wrong, and fix each one.

Maria's grandmother keeps her biryani recipe on a card. The card is a list of steps, and the order matters: you wash the rice before you cook it, never after. A program is the same kind of list. The computer reads it from the top, one line at a time, and does exactly what each line says. This lesson writes the recipe card as a program, and then makes the program do sums.

The recipe card as a program

Here is the card as four lines of JavaScript. Each line prints one step.

console.log("1. Wash the rice.");
console.log("2. Fry the onions until brown.");
console.log("3. Add the meat and the spices.");
console.log("4. Add the rice and cook on low heat.");
1. Wash the rice.
2. Fry the onions until brown.
3. Add the meat and the spices.
4. Add the rice and cook on low heat.

Four lines in, four lines out, in the same order. Each console.log prints its text and then moves to a new line, so you never type the line break yourself.

Each line is a statement: one complete instruction, ending with a semicolon. The engine runs the first statement, then the second, and so on to the last. When it runs out of statements, the program ends.

Statements run top to bottom, and each console.log adds one line to the console The program The console line 1: console.log("1. Wash ..."); line 2: console.log("2. Fry ..."); line 3: console.log("3. Add ..."); line 4: console.log("4. Add ..."); 1. Wash the rice. 2. Fry the onions ... 3. Add the meat ... 4. Add the rice ... each console.log adds one line, in the order the statements run

So a program is a list of statements, run from top to bottom, and the console shows what they printed in that same order.

One statement, piece by piece

Take the first line apart. It has six pieces, and each one has a job.

PieceWhat it is
consoleA ready-made object that Node and every browser give your program. It holds tools for printing.
."Take this from it." The dot reaches inside console for one of its tools.
logThe tool that prints. A tool you run like this is called a function (Module 5).
( ... )The call: run the function now, with what is inside the brackets. What goes inside is called an argument.
"1. Wash the rice."A string: a piece of text, between quotes. The quotes are not printed.
;The end of the statement, like the full stop at the end of a sentence.

A console.log statement

console.log(value1, value2, ...);
  • console.log is the printing function, spelled exactly like this, all in small letters.
  • value1, value2, ... are the arguments: any number of values, separated by commas.
  • The values are printed on one line, with one space between them, and then the line ends.
  • The ; ends the statement. This track always writes it, and lesson 06 explains why.

JavaScript cares about capital letters. console.log works, and Console.log stops the program with an error, as Common mistakes shows. So a statement is pieces in a fixed order, and every piece is spelled exactly.

Several values in one call

console.log takes any number of arguments. It prints them in order, with one space between each pair. A number does not need quotes.

console.log("Rice:", 450, "taka");
console.log("Items:", 3);
console.log(2026);
console.log();
console.log("The line above is empty.");
Rice: 450 taka
Items: 3
2026

The line above is empty.

Look at the first output line. You did not type a space after the colon, and one is there anyway. console.log adds the spaces between arguments, so "Rice:" needs no space of its own. A call with no arguments prints an empty line.

So commas separate the values, and console.log puts the spaces in for you.

Arithmetic: six operators

A number in a program can take part in a sum. Write 120 + 45 and the engine works it out before printing. A piece of code that produces a value, like 120 + 45, is called an expression. The symbol in the middle is an operator.

console.log(120 + 45);
console.log(120 - 45);
console.log(12 * 5);
console.log(7 / 2);
console.log(7 % 2);
console.log(2 ** 10);
165
75
60
3.5
1
1024
OperatorNameExampleResult
+addition120 + 45165
-subtraction120 - 4575
*multiplication12 * 560
/division7 / 23.5
%remainder7 % 21
**power2 ** 101024

The order is the one from school. *, / and % go before + and -, and ** goes before all of them. Brackets go first of all.

console.log(2 + 3 * 4);
console.log((2 + 3) * 4);
console.log(10 - 4 - 3);
console.log(2 * 3 ** 2);
14
20
3
18

2 + 3 * 4 is 2 + 12, and the brackets make it 5 * 4 instead. 10 - 4 - 3 works from the left, so it is 6 - 3. When you are not sure of the order, add brackets: they cost nothing and the next reader thanks you. So an expression is worked out first, in the school order, and only its value reaches console.log.

Division keeps the fraction

7 / 2 printed 3.5. In JavaScript there is one kind of number for whole numbers and decimals alike, so division never throws the fraction away. Lesson 03 shows that one kind of number up close.

When you want the whole part only, say so with Math.floor. It rounds down to the whole number at or below its argument. Math is another ready-made object, like console, full of number tools.

console.log(7 / 2);
console.log(Math.floor(7 / 2));
console.log(10 / 3);
console.log(9 / 3);
3.5
3
3.3333333333333335
3

9 / 3 prints 3, not 3.0, because a whole result prints as a whole number. 10 / 3 ends in a 5 where you might expect a 3. That last digit is real, and lesson 03 explains where it comes from.

If you know C

In C, 7 / 2 between two int values is 3: integer division drops the fraction. JavaScript has no int type, so the same expression is 3.5. A C habit carried over here gives wrong answers with no error. Write Math.floor(a / b) when you mean C's division of positive numbers.

So / always keeps the fraction, and Math.floor is how you drop it on purpose.

Remainder and power

% gives the remainder after division. 17 % 5 is 2, because 5 goes into 17 three times with 2 left over. Its most common job is testing whether a number is even: n % 2 is 0 for an even n and 1 for an odd one.

With a negative number, the sign of the answer follows the left side. Bob expects -7 % 3 to be 2, and it is not.

console.log(17 % 5);
console.log(-7 % 3);
console.log(7 % -3);
console.log(4.5 % 2);
2
-1
1
0.5

-7 % 3 is -1: take 3 out of -7 twice and -1 is left, with the sign of the -7. % also works on decimals, so 4.5 % 2 is 0.5.

** raises a number to a power. 2 ** 10 is ten 2s multiplied together, 1024. A power of 0.5 is a square root, so 2 ** 0.5 prints 1.4142135623730951. So % is the remainder, with the sign of the left side, and ** is the power.

Text in quotes

A string can sit between double quotes or single quotes. "Hello" and 'Hello' are the same string. This track writes double quotes, the default of Prettier, the formatter most JavaScript teams run (lesson 06).

The two kinds help when the text holds a quote. Put the string in the other kind, or put a backslash before the quote.

console.log("It's Zara's turn.");
console.log('She said "go".');
console.log("She said \"go\".");
It's Zara's turn.
She said "go".
She said "go".

The backslash in \" tells the engine that this quote is text, not the end of the string. It is called an escape, and the backslash is not printed. So a string opens and closes with the same kind of quote, and a quote inside it is either the other kind or escaped.

Example 1: the smallest program

One statement is a whole program. Zara runs this one first, in the Playground, before anything else.

console.log("Hello, JavaScript.");
Hello, JavaScript.

There is no setup line and no closing line. The file holds one statement, the engine runs it, and the program ends.

Run in Compiler
Example 2: Kenji's bill, worked out by the program

Kenji buys two notebooks at 60 taka, a pen at 25 and a bag at 450. He lets the program do the sums.

console.log("Notebooks:", 2 * 60);
console.log("Pen:", 25);
console.log("Bag:", 450);
console.log("Total:", 2 * 60 + 25 + 450);
Notebooks: 120
Pen: 25
Bag: 450
Total: 595

2 * 60 + 25 + 450 is 120 + 25 + 450, because * goes first. The labels are strings and the amounts are expressions, side by side in one call.

Run in Compiler
Example 3: minutes into hours and minutes

A film runs 135 minutes, and Amara wants it as hours and minutes. Math.floor gives the whole hours, and % gives the minutes left over.

console.log("Film length:", 135, "minutes");
console.log("That is", Math.floor(135 / 60), "h", 135 % 60, "min");
Film length: 135 minutes
That is 2 h 15 min

135 / 60 is 2.25, and Math.floor makes it 2. 135 % 60 is what is left after two full hours, 15. This pair, Math.floor and %, splits seconds, minutes, centimetres and coins too.

Run in Compiler
Example 4: an average that is not a whole number

Alice has three test marks: 72, 65 and 80. She wants the average, and she wants to see the order of work.

console.log("Sum:", 72 + 65 + 80);
console.log("Average:", (72 + 65 + 80) / 3);
console.log("Without brackets:", 72 + 65 + 80 / 3);
Sum: 217
Average: 72.33333333333333
Without brackets: 163.66666666666666

The brackets make the sum happen first. Without them, only 80 is divided by 3, and the "average" is larger than every mark. That is the first sign of a wrong program: an answer that cannot be true. Module 2 shows how to print 72.33 instead of sixteen digits.

Run in Compiler

Where this is used

  • Chrome DevTools. Every console.log on a web page prints into the Console panel of the browser's developer tools. Frontend developers keep that panel open while they work.
  • Node.js servers. In Node, console.log writes to standard output, the program's main output stream. Docker keeps whatever a container prints there, and docker logs shows it.
  • This track's judge. A judged problem's answer is whatever your program prints to standard output. So console.log is how every answer in this track is handed in.
  • Debugging. A console.log in the middle of a program shows a value at that moment. It is the tool most beginners use first. VS Code also has a real debugger, which pauses a program on a line (Module 17).

Common mistakes

1. Text with no quotes.

console.log(Hello);

On the Playground the run ends with Runtime error and ReferenceError: Hello is not defined. Without quotes, Hello is a name, and nothing has that name yet (lesson 02 makes names). Write console.log("Hello");. You will forget the quotes because the word looks like text to you, and the engine cannot see what you mean.

2. Quotes that do not match.

console.log("Hello');

The program does not start: SyntaxError: Invalid or unexpected token. The string opened with a double quote, so it only ends at another double quote, and there is none. The same message comes from curly quotes pasted from a word processor, such as “Hello”. Use the same straight quote at both ends.

3. A capital C.

Console.log("Hello");

ReferenceError: Console is not defined. JavaScript reads Console and console as two different names, and only the second one exists. You will type the capital because sentences start with one. A typo after the dot, console.lg, gives TypeError: console.lg is not a function instead.

4. A minus sign before a power.

console.log(-2 ** 2);

The program does not start: SyntaxError: Unary operator used immediately before exponentiation expression. Parenthesis must be used to disambiguate operator precedence. Mathematicians and programmers disagree on whether this means 4 or -4, so JavaScript refuses to guess. Write (-2) ** 2 for 4, or -(2 ** 2) for -4.

Brain teaser

Bob has written C before. He predicts this program's four lines before running it, and he gets two of them wrong.

console.log(7 / 2);
console.log(Math.floor(7 / 2));
console.log(7 % 2);
console.log(Math.floor(-7 / 2));

Write down all four lines, then run it. Which two did Bob get wrong, and why the last one?

Reread what Math.floor does: it rounds down. On a number line, which way is down from -3.5?

Exercise 1Easy

David runs a small stall. A customer buys 3 cups of tea at 15 taka, 2 samosas at 20 taka and 1 cake at 55 taka. Print a receipt: one line per item with its cost, then the total. Let the program do every multiplication and the sum.

Output. Exactly these four lines.

Tea: 45
Samosa: 40
Cake: 55
Total: 140
// Print the receipt, one console.log per line.
// Write the costs as sums, such as 3 * 15, not as 45.

Not graded. Compare your output with the four lines above, character by character.

Run in Compiler
Exercise 2Easy

Zara is fencing a garden that is 12 metres long and 5 metres wide. She needs its area, for the grass seed, and its perimeter, for the fence.

Output. Exactly these two lines.

Area: 60
Perimeter: 34
// The area is length times width.
// The perimeter is twice the length plus twice the width.
// Use brackets where the order matters.

Not graded. Then change 12 to 12.5 and check both answers by hand.

Run in Compiler

Common doubts

  • Why console.log and not just print?

    JavaScript was made for web pages, and the language itself has no printing statement. The browser and Node each hand your program a console object to print with. In a browser, print() already means something else: it opens the dialog that prints the page on paper.

  • Do I have to write the semicolon?

    Often the program runs without it, because the engine adds missing semicolons by a set of rules. Those rules have one case that surprises people. This track writes every semicolon, and lesson 06 shows the case.

  • Is "450" the same as 450?

    No. The first is text that happens to show digits, and the second is a number. console.log prints them the same way, which hides the difference. + does not treat them the same, as Module 2 shows.

  • Why does 10 / 3 end in 5?

    A number in JavaScript is stored in binary, and most decimal fractions cannot be stored exactly. The last digit shows the tiny difference. Lesson 03 shows the famous case, 0.1 + 0.2.

Key takeaways

  • A program is a list of statements, run from top to bottom; each ends with a semicolon.
  • console.log prints its arguments on one line with spaces between, then ends the line.
  • The six operators are + - * / % **, worked out in the school order; brackets go first.
  • / keeps the fraction, so 7 / 2 is 3.5; Math.floor drops it on purpose, and % is the remainder, with the sign of the left side.
  • A string sits between matching quotes; this track writes double quotes.
  • A typo stops the program with Node's message: a SyntaxError before it starts, a ReferenceError or TypeError on the line that failed.

Next, lesson 02 gives a value a name, so a program can keep a number and change it later.

End of lesson 1

Mark it done, and your progress moves with you.

Next: let and const: A Name for a Value, and Why Not var