Bitpath

Lesson 2 · Unit 06

Modules and data

Several files, JSON, Map, Set and a first Date

13 exercisesabout 3 min

What you practise

  • export and import, JSON.stringify and JSON.parse, Map and Set, copying against sharing, a first look at Date

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?

JavaScript
const user = { name: "Ada", age: 36 };
const text = JSON.stringify(user);
console.log(typeof text);

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.

JavaScript
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]); // a

Concept

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.

JavaScript
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")); // false

Concept

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.

One email when Bitpath is ready to try. Nothing else. Privacy