Skip to main content
Module 4 · Lesson 4 of 416/32 in the course~18 min
Module lessons (4/4)

Closures and scope

Lesson preview5 hands-on exercises readyJavaScript Course · Module 4 — Functions

Functions that remember their environment: counters, factories, scope chain.

What you'll learn in this lesson

  • Understand how the Lexical Scope Chain works (searching from the inside out).
  • Understand what a closure is: a function combined with its lexical environment retained in the Heap even after the external function ends.
  • Construct factories with encapsulated private state (makeCounter, makeRateLimiter, configurators).
  • Fix the classic loop bug with var by using let to get an isolated binding for each iteration.

Overview

A closure arises automatically every time a function defined inside another block or function accesses variables of that external scope: the internal function carries with it a live reference to those variables in the Heap even after the creating function has left the Call Stack.

Sections covered in this lesson

  1. 1Mental model: lexical backpack (Closure Cell)
  2. 2Progressive examples
  3. 3Guided laboratory
  4. 4Check for understanding
Pro Lesson · Module 4 — Functions

Unlock "Closures and scope" and the full JavaScript Course curriculum

Functions that remember their environment: counters, factories, scope chain.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in JavaScript Course plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.