Lesson 2 · Unit 06
Modules and data
Several files, JSON, Map, Set and a first Date
What you practise
exportandimport,JSON.stringifyandJSON.parse,MapandSet, copying against sharing, a first look atDate
Try a question from this lesson
Pick one
JSON.stringify writes a value out as text, so that it can be saved in a file or sent over a network. What prints?
const user = { name: "Ada", age: 36 };
const text = JSON.stringify(user);
console.log(typeof text);Correct answer
string
Why
The result is an ordinary string that happens to look like an object: {"name":"Ada","age":36}. Files and networks can only carry text, so data has to be written out like this before it leaves your program.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
JSON: data as text
JSON is a way of writing objects, arrays, strings, numbers, true, false and null as text. It looks like JavaScript, with every key in double quotes.
JSON.stringify(value) writes the text. JSON.parse(text) reads it back and builds brand-new objects from it.
const user = { name: "Ada", tags: ["a"] };
const text = JSON.stringify(user);
console.log(text);
// {"name":"Ada","tags":["a"]}
const back = JSON.parse(text);
console.log(back.tags[0]); // aConcept
Set and Map
A Set is a collection where every value appears once. Add one that is already there and nothing happens.
A Map links keys to values, like an object. Unlike an object, it is built for the job: any value can be a key, it knows its size, and it starts truly empty.
const seen = new Set(["a", "b", "a"]);
console.log(seen.size); // 2
console.log(seen.has("b")); // true
const stock = new Map();
stock.set("tea", 4);
console.log(stock.get("tea")); // 4
console.log(stock.has("jam")); // falseConcept
Modules: one file, one job
A program grows past one file. Each file is a module with its own names: nothing leaks out by accident.
export marks what other files may use. import brings those things in by name, from the path of the file.
Below are two files of one program. Running main.js prints 8.2.
// math.js
export function double(n) {
return n * 2;
}
export const TAX = 0.2;
// main.js
import { double, TAX } from "./math.js";
console.log(double(4) + TAX);9 more exercises in the app
- 3× type the answer
- 4× multiple choice
- 1× fill the blanks
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.