appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Modules, scope and closures

Lesson 3 of 411 minIntermediate

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.

math.js
export const TAX = 0.21;
export function withTax(price) { return price * (1 + TAX); }
export default function round2(n) { return Math.round(n * 100) / 100; }
main.js
import round2, { withTax } from "./math.js";
console.log(round2(withTax(10)));
index.html
<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 const by default and let when a value changes. Avoid var: it ignores block scope.
  • Each call to counter() creates a separate n.
  • 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.

1. What is a closure?
2. How do you load a module in the browser?
3. Which keyword should be your default for a variable that does not change?

Key terms