Chapter 2 · Decide, repeat, reuse

Modules and input

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 22 · Concept

A module is a file of functions

By the end of this lesson your programs span several files, and read files and input.

Each .js file is a module. shapes.js writes export before its function, so other files may use it. main.js takes it with import:

import { area } from "./shapes.js";

./ means this folder, and the .js is required. Write import lines at the top of the file.

import { area, perimeter } from "./shapes.js";

console.log(area(2, 3), perimeter(2, 3));
import { area, perimeter } from "./shapes.js";

console.log(area(2, 3), perimeter(2, 3));
import { greet } from "./greet.js";
import { area } from "./shapes.js";
console.log(greet("Ada"), area(2, 3));
const roll = Math.floor(Math.random() * 6) + 1;
console.log("In range:", roll >= 1 && roll <= 6);
import { readFileSync } from "node:fs";

const names = readFileSync("names.txt", "utf8").trim();
console.log(names);
console.log("Characters:", names.length);
import { readFileSync } from "node:fs";

const age = readFileSync(0, "utf8").trim();
console.log(age + 1);
import { readFileSync } from "node:fs";

const age = readFileSync(0, "utf8").trim();
console.log("Next year:", age + 1);
// 1. import tip from money.js
// 2. read the bill from the input
// 3. log Tip: and Total:
// read the quantity, then log its cost
// import all of shapes.js as shapes

console.log(shapes.area(2, 3), shapes.perimeter(2, 3));
console.log(shapes.square(4));
Terminal
Step 1 of 10Two files, one program

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)