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:
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.
// A different quote for each day: change today from 0 to 3constquotes=["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.",];consttoday=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
Console
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
Choose a website you use often, open it, and press F12.
In Elements, find the main heading. Which element is it (h1, h2, a div…)? Look up that element on MDN.
In Network, reload the page. Write down: how many requests, how much data was transferred, and the type of the largest file.
In Console, type document.title and press Enter. What do you get?
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.
#!/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-pcode-from-zero
echo'$ cd code-from-zero'cdcode-from-zero
echo'$ mkdir chapter-03'
mkdirchapter-03
echo'$ cd chapter-03'cdchapter-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.
// 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 tableconsole.table([{name:"Book",price:12},{name:"Mug",price:8},]);// count: how many times this line has runconsole.count("clicks");console.count("clicks");console.count("clicks");// time and timeEnd: how long something took (the number differs on every run)console.time("loop");lettotal=0;for(leti=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
Console
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.
<!DOCTYPE html><htmllang="en"dir="ltr"><head><metacharset="utf-8"><metaname="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:24pxauto;padding:016px;}table{border-collapse:collapse;width:100%;}th,td{border-bottom:1pxsolid#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><imgsrc="../../../ch05/examples/bit.svg"alt="Bit, the robot"width="96"><pid="summary"></p><table><thead><tr><th>File</th><th>Type</th><th>Size (bytes)</th></tr></thead><tbodyid="list"></tbody></table><script>window.addEventListener("load",()=>{// The page itself is a request too.constpage=performance.getEntriesByType("navigation")[0];constfiles=[page,...performance.getEntriesByType("resource")];constsize=(f)=>f.transferSize||f.encodedBodySize||0;constlargest=files.reduce((a,b)=>(size(b)>size(a)?b:a));document.querySelector("#summary").textContent=`Requests: ${files.length}. Largest file: ${largest.name.split("/").pop()||"/"}`;for(constfoffiles){constrow=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>
// 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.constfiles=performance.getEntriesByType("resource");constsorted=[...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.
#!/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'
mkdirpractice
echo'$ code practice/test.js'printf'console.log(365 * 24);\n'>practice/test.js
echo'$ cat practice/test.js'
catpractice/test.js
echo'$ node practice/test.js'
nodepractice/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).