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

Chapter 3

Your Developer Toolkit

6 examples · 3 projects · 5 exercises

In this chapter you will

  • install and set up Visual Studio Code, a free professional code editor
  • learn the handful of terminal commands every developer uses daily
  • install Node.js and run a JavaScript file on your own computer
  • create the project folder you will use for the rest of this book
  • meet the browser’s developer tools and learn where to find good help

Examples

3.1 The code editor

Open the extensions view, search for Prettier and click Install. Prettier is a formatter: every time you save, it neatly arranges spaces and line breaks in your code, so you never have to worry about them. Then open the settings file with Ctrl + Shift + P (Cmd + Shift + P on a Mac), type Open User Settings (JSON), and add these lines:

settings.json⤓ File
{
  "editor.fontSize": 16,
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "files.autoSave": "onFocusChange",
  "editor.wordWrap": "on"
}

3.2 The terminal

The terminal shows a prompt, often ending in $ or >, and waits for you to type. In this book, a line that starts with $ is a command for you to type (without the $), and the lines below it are what the computer answers.

navigate.sh⤓ File
Terminal session from the book
$ pwd
/Users/sara
$ ls
Desktop    Documents    Downloads    code-from-zero
$ cd code-from-zero
$ pwd
/Users/sara/code-from-zero
$ cd ..

3.3 Installing Node.js

Check that everything works by asking for the version numbers:

versions.sh⤓ File
Terminal session from the book
$ node --version
v22.12.0
$ npm --version
10.9.0

3.4 Your first project

Developers keep each project in its own folder. Let us create the folder you will use for every example in this book:

first-project.sh⤓ File
Terminal session from the book
# Make a folder for the book, go into it, and open it in VS Code
$ mkdir code-from-zero
$ cd code-from-zero
$ code .

In the VS Code Explorer, click the New File icon, name the file check.js, and type:

check.js⤓ File
console.log("Node.js is working!");
console.log(`2 + 2 = ${2 + 2}`);
Recorded output$ node check.js
Node.js is working!
2 + 2 = 4

Save it, open the terminal panel in VS Code, and run it:

run.sh⤓ File
Terminal session from the book
$ node check.js
Node.js is working!
2 + 2 = 4

Practice projects

Project 3.1 · Easy

A folder for your notes, terminal only

Create a folder structure for your notes on this book, moving around it using only the terminal.

You will practise: cd, mkdir, ls, pwd, the Up arrow and Tab.

Steps
  1. Open the terminal and go into code-from-zero.
  2. Create a folder called book-notes and go into it.
  3. Create four folders, part-1 to part-4, with one command: mkdir accepts several names separated by spaces.
  4. Go into part-1, check where you are with pwd, and come back up two levels with cd .. twice.
  5. Use the Up arrow to repeat a command, and Tab to complete a folder name, at least once each.

Hint: if you get lost, pwd always tells you where you are. Your folder paths will start differently, depending on your computer and your user name.

Solution
folders.sh⤓ File
Terminal session from the book
$ cd code-from-zero
$ mkdir book-notes
$ cd book-notes
$ mkdir part-1 part-2 part-3 part-4
$ ls
part-1    part-2    part-3    part-4
$ cd part-1
$ pwd
/Users/sara/code-from-zero/book-notes/part-1
$ cd ..
$ cd ..
$ pwd
/Users/sara/code-from-zero

Project 3.2 · Easy

Quote of the day

Write a small program that prints an encouraging programming quote, and run it from VS Code’s own terminal.

You will practise: creating and running files, the VS Code terminal, Prettier, and a first look at lists.

Steps
  1. In VS Code, create quote.js in your code-from-zero folder.
  2. Write a list of four quotes between square brackets, separated by commas, as in the solution below. You will learn lists properly in Chapter 9.
  3. Print a title, then quotes[today], where today is a number from 0 to 3.
  4. Mess up the spacing on purpose, then save: watch Prettier tidy it up.
  5. Open the terminal with Ctrl + ` and run node quote.js. Change today and run it again with the Up arrow.

Hint: the first quote is number 0, not 1. That surprises everybody at first; Chapter 9 explains why.

Solution
quote.js⤓ File
// A different quote for each day: change today from 0 to 3
const quotes = [
  "First, solve the problem. Then, write the code.",
  "Every expert was once a beginner.",
  "Small steps every day beat big steps once a month.",
  "Read the error message. All of it.",
];

const today = 2;

console.log("Quote of the day:");
console.log(quotes[today]);
console.log("Quotes in the list:", quotes.length);
Recorded output$ node quote.js
Quote of the day:
Small steps every day beat big steps once a month.
Quotes in the list: 4

Project 3.3 · Medium

DevTools detective

Investigate a real website with the browser’s developer tools, and write a short report of what you find.

You will practise: the Elements, Console and Network panels, and looking things up on MDN.

Steps
  1. Choose a website you use often, open it, and press F12.
  2. In Elements, find the main heading. Which element is it (h1, h2, a div…)? Look up that element on MDN.
  3. In Network, reload the page. Write down: how many requests, how much data was transferred, and the type of the largest file.
  4. In Console, type document.title and press Enter. What do you get?
  5. Write your findings in a file called detective.txt in your book-notes folder, as a short table: question, answer.

Hint: the Network panel shows the totals at the bottom: number of requests, data transferred and the time the page took to load. Tick Disable cache to see a “first visit” load.

Solution

Exercises

Exercise 3.1 · Easy

In the terminal, go into your code-from-zero folder, create a folder called chapter-03 with mkdir, go into it, and check where you are with pwd.
The book's short answer
cd code-from-zero, mkdir chapter-03, cd chapter-03, pwd.
Show the solution
terminal.sh⤓ File
Runs in a terminal: bash terminal.sh
#!/usr/bin/env bash
# Exercise 3.1: the commands, one per line. Run it with: bash terminal.sh
# It works inside a temporary folder so it leaves nothing behind. On your own computer, start in your home folder instead.
set -e
cd "$(mktemp -d)"
mkdir -p code-from-zero

echo '$ cd code-from-zero'
cd code-from-zero
echo '$ mkdir chapter-03'
mkdir chapter-03
echo '$ cd chapter-03'
cd chapter-03
echo '$ pwd'
pwd | sed 's#.*/code-from-zero#~/code-from-zero#'
echo '$ ls ..'
ls ..
Recorded output$ bash terminal.sh
$ cd code-from-zero
$ mkdir chapter-03
$ cd chapter-03
$ pwd
~/code-from-zero/chapter-03
$ ls ..
chapter-03

Exercise 3.2 · Easy

Create me.js that prints your name, your city and your favourite food on three lines. Run it with Node.js.
The book's short answer
Three console.log lines with your own text, run with node me.js.
Show the solution
me.js⤓ File
console.log("My name is Sara");
console.log("I live in Alexandria");
console.log("My favourite food is koshari");
Recorded output$ node me.js
My name is Sara
I live in Alexandria
My favourite food is koshari

Exercise 3.3 · Medium

Find the MDN page for console.log. What other console commands does it list? Try console.error and console.table.
The book's short answer
Among others: console.error, console.warn, console.table, console.info, console.count, console.time.
Show the solution
console-tour.js⤓ File
// A tour of the console commands listed on MDN's page for console.
// In the terminal, error and warn go to "standard error"; in the browser they are shown in red and yellow.

console.log("log: an ordinary message");
console.info("info: information, the same as log in Node");
console.warn("warn: a warning");
console.error("error: an error message");

// table: an array of objects shown as a table
console.table([
  { name: "Book", price: 12 },
  { name: "Mug", price: 8 },
]);

// count: how many times this line has run
console.count("clicks");
console.count("clicks");
console.count("clicks");

// time and timeEnd: how long something took (the number differs on every run)
console.time("loop");
let total = 0;
for (let i = 0; i < 1000000; i++) {
  total = total + i;
}
console.timeEnd("loop");
console.log(total);
Recorded output$ node console-tour.js
log: an ordinary message
info: information, the same as log in Node
warn: a warning
error: an error message
┌─────────┬────────┬───────┐
│ (index) │ name   │ price │
├─────────┼────────┼───────┤
│ 0       │ 'Book' │ 12    │
│ 1       │ 'Mug'  │ 8     │
└─────────┴────────┴───────┘
clicks: 1
clicks: 2
clicks: 3
loop: 5.272ms
499999500000

Exercise 3.4 · Medium

Open any website’s DevTools, choose Network, and reload the page. How many requests did it make? Which was the largest file?
The book's short answer
It depends on the website; large news sites often make more than a hundred requests, and the largest files are usually images, videos or JavaScript bundles.
Show the solution
network.html↗ Open page⤓ File
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>What did this page download?</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 720px; margin: 24px auto; padding: 0 16px; }
    table { border-collapse: collapse; width: 100%; }
    th, td { border-bottom: 1px solid #ddd; padding: 6px; text-align: start; }
    .big { background: #fef3c7; }
  </style>
</head>
<body>
  <h1>What did this page download?</h1>
  <p>The Network tab shows every request a page makes. A page can ask the browser for the same list with <code>performance.getEntriesByType("resource")</code>. This page loads a picture and a stylesheet, then lists its own requests.</p>
  <img src="../../../ch05/examples/bit.svg" alt="Bit, the robot" width="96">
  <p id="summary"></p>
  <table>
    <thead><tr><th>File</th><th>Type</th><th>Size (bytes)</th></tr></thead>
    <tbody id="list"></tbody>
  </table>
  <script>
    window.addEventListener("load", () => {
      // The page itself is a request too.
      const page = performance.getEntriesByType("navigation")[0];
      const files = [page, ...performance.getEntriesByType("resource")];
      const size = (f) => f.transferSize || f.encodedBodySize || 0;
      const largest = files.reduce((a, b) => (size(b) > size(a) ? b : a));
      document.querySelector("#summary").textContent =
        `Requests: ${files.length}. Largest file: ${largest.name.split("/").pop() || "/"}`;
      for (const f of files) {
        const row = document.createElement("tr");
        if (f === largest) row.className = "big";
        row.innerHTML = `<td>${f.name.split("/").pop() || "/"}</td><td>${f.initiatorType}</td><td>${size(f)}</td>`;
        document.querySelector("#list").append(row);
      }
    });
  </script>
</body>
</html>
network.html640px
snippet.js⤓ File
Paste into the browser's Console
// Paste this into the Console of any website, after it has loaded.
// It counts the requests and finds the largest file, like the Network tab does.
const files = performance.getEntriesByType("resource");
const sorted = [...files].sort((a, b) => b.transferSize - a.transferSize);
console.log(`Requests: ${files.length + 1}`);
console.table(sorted.slice(0, 5).map((f) => ({ file: f.name.slice(0, 80), type: f.initiatorType, bytes: f.transferSize })));

Exercise 3.5 · Challenge

Use only the terminal (no mouse) to create a folder practice, create a file inside it with the command code practice/test.js, write a program that prints the result of 365 * 24, and run it. What does the number mean?
The book's short answer
mkdir practice, code practice/test.js, write console.log(365 * 24);, run node practice/test.js. 8760 is the number of hours in a (non-leap) year.
Show the solution
practice.sh⤓ File
Runs in a terminal: bash practice.sh
#!/usr/bin/env bash
# Exercise 3.5 with the keyboard only. Run it with: bash practice.sh
# "code practice/test.js" opens the file in VS Code; a script cannot type into an editor, so it writes the line with printf.
set -e
cd "$(mktemp -d)"

echo '$ mkdir practice'
mkdir practice
echo '$ code practice/test.js'
printf 'console.log(365 * 24);\n' > practice/test.js
echo '$ cat practice/test.js'
cat practice/test.js
echo '$ node practice/test.js'
node practice/test.js
echo "# 8760 is the number of hours in a year that is not a leap year (365 days × 24 hours)."
Recorded output$ bash practice.sh
$ mkdir practice
$ code practice/test.js
$ cat practice/test.js
console.log(365 * 24);
$ node practice/test.js
8760
# 8760 is the number of hours in a year that is not a leap year (365 days × 24 hours).