You Don’t Know JS Yet: Scope & Closures
Welcome to the second book in the You Don’t Know JS Yet series! This book dives deep into one of the most fundamental aspects of JavaScript: lexical scope and closures.
What You’ll Learn
This book explores the first of three pillars in the JavaScript language:Lexical Scope
Understanding how the JS engine determines variable access and scope boundaries during compilation
Closures
Leveraging function closures to maintain state and create powerful design patterns
Module Pattern
Organizing code with proper encapsulation using classic modules, CommonJS, and ES modules
POLE Principle
Applying the Principle of Least Exposure to write more maintainable and secure code
Why Scope Matters
JS is typically classified as an interpreted scripting language, but it’s actually parsed and compiled in a separate phase before execution begins. Understanding this two-phase processing is critical to mastering scope.
- Structure your programs more effectively
- Avoid common pitfalls like variable collisions and TDZ errors
- Leverage powerful patterns like memoization and the module pattern
- Write more maintainable and debuggable code
Book Contents
Understanding Scope
Learn how JavaScript’s compilation process determines scope, and master the difference between targets and sources.
Visualizing Scope
Use metaphors like colored marbles and scope bubbles to build accurate mental models.
Scope Chain & Shadowing
Explore how nested scopes create a chain and understand variable shadowing behavior.
Global Scope Nuances
Discover how the global scope works differently across browsers, Node, and ES modules.
Variable Lifecycle
Master hoisting, TDZ, and the differences between var, let, and const declarations.
Limiting Exposure
Apply POLE to reduce scope over-exposure using functions, IIFEs, and block scoping.
Mastering Closures
Understand how functions remember their lexical scope and leverage closure for powerful patterns.
Get the Book
Purchase the Book
Get the complete ebook/PDF from Leanpub
Chapters
Explore each chapter to deepen your understanding:- Foreword by Sarah Drasner
- Chapter 1: What’s the Scope?
- Chapter 2: Illustrating Lexical Scope
- Chapter 3: The Scope Chain
- Chapter 4: Around the Global Scope
- Chapter 5: The (Not So) Secret Lifecycle of Variables
- Chapter 6: Limiting Scope Exposure
- Chapter 7: Using Closures
- Chapter 8: The Module Pattern
- Appendix A: Exploring Further
- Appendix B: Practice

