Modules, scope and closures
Split code into files and understand how functions remember their surroundings.
ES modules
A module is a file with its own scope. It shares what it chooses with export and uses other modules with import.
export const TAX = 0.21;
export function withTax(price) { return price * (1 + TAX); }
export default function round2(n) { return Math.round(n * 100) / 100; }import round2, { withTax } from "./math.js";
console.log(round2(withTax(10)));<script type="module" src="main.js"></script>Closures
A function keeps access to the variables of the place where it was created, even after that place has finished. That is a closure.
function counter() {
let n = 0;
return () => ++n;
}
const next = counter();
next(); // 1
next(); // 2 (n is private: nothing else can touch it)- Use
constby default andletwhen a value changes. Avoidvar: it ignores block scope. - Each call to
counter()creates a separaten. - Closures power callbacks, event handlers and many patterns such as private state.
CarefulA closure keeps its variables alive. An event listener that you never remove and that refers to a large object can cause a memory leak.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.