From Zero to Senior · The LabالعربيةGitHub

Chapter 1

How Computers Run Programs

3 examples · 3 projects · 5 exercises

In this chapter you will learn

  • what a program really is
  • the four main parts inside every computer, and what each one does
  • why computers store everything, even letters and pictures, as numbers
  • how the code you write becomes something a processor can run
  • how to run your very first line of JavaScript

Examples

1.3 Everything is a number

You will almost never write binary yourself; the computer handles it for you. But JavaScript can show you what a number looks like in binary, and we can check the table:

binary.js⤓ File
console.log((5).toString(2));
console.log((13).toString(2));
console.log((255).toString(2));
console.log(parseInt("1101", 2));
Recorded output$ node binary.js
101
1101
11111111
13

If everything is a number, how does a computer store the letter A? It uses an agreed table that gives every character a number. The modern table is called Unicode, and it contains more than 150,000 characters from almost every writing system in the world, including Arabic, Chinese, and even emoji.

letters.js⤓ File
console.log("A".charCodeAt(0));
console.log("a".charCodeAt(0));
console.log("ب".charCodeAt(0));
console.log(String.fromCharCode(72, 105));
Recorded output$ node letters.js
65
97
1576
Hi

1.5 Your first line of code

You do not have to wait until Chapter 3 to try JavaScript. Every browser has a hidden tool for developers. Open Chrome, Edge or Firefox, then press F12 (on a Mac, press Cmd + Option + J). A panel opens; click the tab called Console. Type each of these lines and press Enter after each one:

hello.js⤓ File
console.log("Hello, world!");
console.log(2 + 3);
console.log("2" + "3");
Recorded output$ node hello.js
Hello, world!
5
23

Practice projects

Project 1.1 · Easy

Your life in numbers

Write a program that tells you how many months, days, hours and minutes you have been alive (roughly).

You will practise: running JavaScript, numbers and the * operator, and printing several values.

Steps
  1. Create a file called my-numbers.js in your code-from-zero folder, or open the browser console.
  2. Write const age = 20; on the first line, with your own age instead of 20.
  3. Print the number of months: console.log("Months:", age * 12);. Notice that console.log can print a label and a number together, separated by a comma.
  4. Add three more lines for days (age * 365), hours and minutes. Each one multiplies the line before by a little more.
  5. Run the program and check one answer with a calculator.

Hint: hours are days × 24, and minutes are hours × 60, so the minutes line is age * 365 * 24 * 60.

Solution
my-numbers.js⤓ File
// Change 20 to your own age
const age = 20;

console.log("Months:", age * 12);
console.log("Days:", age * 365);
console.log("Hours:", age * 365 * 24);
console.log("Minutes:", age * 365 * 24 * 60);
Recorded output$ node my-numbers.js
Months: 240
Days: 7300
Hours: 175200
Minutes: 10512000

Project 1.2 · Easy

A secret code in Unicode

Turn a name into secret numbers, and the numbers back into the name, using the Unicode table from Section 1.3.

You will practise: charCodeAt, String.fromCharCode and the idea that letters are numbers.

Steps
  1. Print the Unicode number of each letter of Bit: "B".charCodeAt(0), then "i", then "t", all in one console.log separated by commas.
  2. Now decode: String.fromCharCode(66, 105, 116) should print the name again.
  3. The Arabic name بِت has three characters too: the letter ب, the small vowel mark under it (a kasra), and ت. Their numbers are 1576, 1616 and 1578. Decode them the same way.
  4. Send a friend a “secret message” as numbers and ask them to decode it with the browser console.

Hint: vowel marks such as the kasra are separate characters in Unicode, with their own numbers. That is why the Arabic name needs three numbers even though you see two letters.

Solution
secret-code.js⤓ File
// Turn each letter into its Unicode number
console.log("B".charCodeAt(0), "i".charCodeAt(0), "t".charCodeAt(0));

// And back again: numbers into letters
console.log(String.fromCharCode(66, 105, 116));
console.log(String.fromCharCode(1576, 1616, 1578));
Recorded output$ node secret-code.js
66 105 116
Bit
بِت

Project 1.3 · Medium

Your birthday in binary

Show the day, month and year of a birthday in binary, and check the result by turning it back.

You will practise: toString(2), parseInt and checking your own work.

Steps
  1. Create three constants: day, month and year, with a birthday you like.
  2. Print each one in binary with .toString(2), with a label.
  3. Before running the program, work out the day in binary on paper, using the table in Section 1.3. Did you get the same answer as the computer?
  4. Prove that the conversion is correct: turn the year’s binary back into a normal number with parseInt(year.toString(2), 2). It must print the year again.

Hint: checking a result by converting it back is a habit professionals use everywhere: encode and decode, save and load, send and receive.

Solution
binary-birthday.js⤓ File
const day = 14;
const month = 3;
const year = 2008;

console.log("Day in binary:", day.toString(2));
console.log("Month in binary:", month.toString(2));
console.log("Year in binary:", year.toString(2));
console.log("Check, back to decimal:", parseInt(year.toString(2), 2));
Recorded output$ node binary-birthday.js
Day in binary: 1110
Month in binary: 11
Year in binary: 11111011000
Check, back to decimal: 2008

Exercises

Exercise 1.1 · Easy

Name the four main parts of a computer, and give one example of input and one of output.
The book's short answer
Processor, memory, storage, and input and output. Input: keyboard, mouse, touch screen, microphone. Output: screen, speakers, printer.
Show the solution
parts.js⤓ File
// The four main parts of every computer, with what each one does.
console.log("1. Processor (CPU): runs the instructions");
console.log("2. Memory (RAM): fast, forgets everything when the power is off");
console.log("3. Storage (SSD): slower, keeps files when the power is off");
console.log("4. Input and output: connect the computer to the world");
console.log("");
console.log("Input examples: keyboard, mouse, touch screen, microphone");
console.log("Output examples: screen, speakers, printer");
console.log("The network does both.");
Recorded output$ node parts.js
1. Processor (CPU): runs the instructions
2. Memory (RAM): fast, forgets everything when the power is off
3. Storage (SSD): slower, keeps files when the power is off
4. Input and output: connect the computer to the world

Input examples: keyboard, mouse, touch screen, microphone
Output examples: screen, speakers, printer
The network does both.

Exercise 1.2 · Easy

Using the table in Section 1.3, what is 9 in binary? Check your answer with (9).toString(2) in the browser console.
The book's short answer
9 is 1001 in binary (8 + 1).
Show the solution
nine.js⤓ File
// 9 = 8 + 1, so it needs the 8 column and the 1 column: 1001
console.log((9).toString(2));

// And back again, to be sure
console.log(parseInt("1001", 2));

// The numbers around it, to see the pattern
console.log((8).toString(2), (9).toString(2), (10).toString(2));
Recorded output$ node nine.js
1001
9
1000 1001 1010

Exercise 1.3 · Medium

Find the Unicode number of the first letter of your name with "X".charCodeAt(0), replacing X with your letter.
The book's short answer
It depends on the letter: for example "S".charCodeAt(0) is 83 and "س".charCodeAt(0) is 1587.
Show the solution
my-letter.js⤓ File
// Put the first letter of your own name between the quotes.
console.log("S".charCodeAt(0));
console.log("س".charCodeAt(0));

// Capital and small letters are different numbers:
console.log("s".charCodeAt(0));

// And back from the number to the letter:
console.log(String.fromCharCode(83), String.fromCharCode(1587));
Recorded output$ node my-letter.js
83
1587
115
S س

Exercise 1.4 · Medium

Predict what each line prints, then check in the console: console.log(10 + 5), console.log("10" + "5"), console.log("10 + 5").
The book's short answer
15, then 105 (two strings joined), then the text 10 + 5 (everything between the quotes is printed as it is).
Show the solution
predict.js⤓ File
// Prediction: 15 (two numbers are added)
console.log(10 + 5);

// Prediction: 105 (two pieces of text are joined, not added)
console.log("10" + "5");

// Prediction: the text 10 + 5 (everything between the quotes is printed as it is)
console.log("10 + 5");
Recorded output$ node predict.js
15
105
10 + 5

Exercise 1.5 · Challenge

Write the steps for making a cup of tea so precisely that a robot who knows nothing could follow them. Then ask a friend to find a step a robot could misunderstand.
The book's short answer
A good answer says exactly how much water, which cup, when to stop boiling, how long to wait, and what to do if something is missing. Words like “some” or “a bit” are the steps a robot would misunderstand.
Show the solution

Making a cup of tea, for a robot

Every step says exactly what, how much and when. Nothing is left to guess.

  1. Take the white mug from the second shelf of the cupboard above the sink.
  2. Take the kettle. Open its lid.
  3. Hold the kettle under the cold tap and fill it to the 0.5 litre line. Close the tap.
  4. Close the lid. Put the kettle on its base and press the switch down.
  5. Wait until the switch jumps up by itself (about 3 minutes). If it has not jumped up after 6 minutes, stop and call a human.
  6. Take one tea bag from the red box. If the box is empty, stop and say "No tea bags".
  7. Put the tea bag in the mug, with its string hanging outside.
  8. Pour water from the kettle into the mug until it is 1 cm below the rim.
  9. Wait 3 minutes.
  10. Pull the tea bag out by its string and put it in the bin.
  11. Add 1 teaspoon of sugar and stir 5 times.

Words a robot would misunderstand, and that this list avoids: "some water", "a bit of sugar", "until it is ready", "a cup" (which one?).

Run node robot.js to let a strict robot check the steps for you.

robot.js⤓ File
// A strict robot: it reads each step and complains about every word it cannot measure.
// (You will understand every line of this program by Chapter 9. For now, run it and read what it says.)

const vague = ["some", "a bit", "a little", "enough", "until ready", "a cup", "hot"];

const vagueSteps = [
  "Put some water in the kettle",
  "Boil it until ready",
  "Put a tea bag in a cup",
  "Add a bit of sugar",
];

const preciseSteps = [
  "Fill the kettle to the 0.5 litre line",
  "Press the switch and wait until it jumps up by itself",
  "Put one tea bag in the white mug",
  "Add 1 teaspoon of sugar and stir 5 times",
];

function check(title, steps) {
  console.log(`== ${title}`);
  let problems = 0;
  steps.forEach((step, i) => {
    const found = vague.filter((word) => step.includes(word));
    if (found.length > 0) {
      problems++;
      console.log(`Step ${i + 1}: "${step}" -> I do not understand: ${found.join(", ")}`);
    } else {
      console.log(`Step ${i + 1}: OK`);
    }
  });
  console.log(problems === 0 ? "I can make this tea!" : `Unclear steps: ${problems}`);
  console.log("");
}

check("A friend's first try", vagueSteps);
check("Our precise steps", preciseSteps);
Recorded output$ node robot.js
== A friend's first try
Step 1: "Put some water in the kettle" -> I do not understand: some
Step 2: "Boil it until ready" -> I do not understand: until ready
Step 3: "Put a tea bag in a cup" -> I do not understand: a cup
Step 4: "Add a bit of sugar" -> I do not understand: a bit
Unclear steps: 4

== Our precise steps
Step 1: OK
Step 2: OK
Step 3: OK
Step 4: OK
I can make this tea!