0% found this document useful (0 votes)
109 views128 pages

You Don't Know JS Yet PDF

Uploaded by

924957
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views128 pages

You Don't Know JS Yet PDF

Uploaded by

924957
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

You Don't Know JS Yet PDF

Kyle Simpson

Scan to Download
You Don't Know JS Yet
Master JavaScript Fundamentals with Clarity and
Confidence.
Written by Bookey
Check more about You Don't Know JS Yet Summary
Listen You Don't Know JS Yet Audiobook

Scan to Download
About the book
In an era where the demand for a deeper understanding of
JavaScript has reached unprecedented heights, finding the
right resources amidst the overwhelming sea of blogs, books,
and videos can be a daunting task. Enter "You Don't Know JS
Yet," the highly anticipated sequel to the bestselling "You
Don't Know JS" series by Kyle Simpson. This updated
collection, consisting of six meticulously rewritten volumes,
provides a comprehensive exploration of JavaScript as it
stands in 2020 and beyond. The first book, "Get Started," sets
the stage for your journey, offering an overview of the
language and outlining how the entire series will enrich your
understanding and mastery of JavaScript.

Scan to Download
About the author
Kyle Simpson is an Open Web Evangelist based in Austin,
TX, with a deep passion for JavaScript and its ecosystem. As
an accomplished author, workshop trainer, and tech speaker,
he actively engages with the developer community and
contributes to open-source projects, inspiring others to
embrace the power of the web.

Scan to Download
Summary Content List
Chapter 1 : You Don't Know JS Yet: Scope & Closures

Chapter 2 : What’s the Scope?

Chapter 3 : Illustrating Lexical Scope

Chapter 4 : The Scope Chain

Chapter 5 : Around the Global Scope

Chapter 6 : The (Not So) Secret Lifecycle of Variables

Chapter 7 : Limiting Scope Exposure

Chapter 8 : Using Closures

Chapter 9 : The Module Pattern

Chapter 10 : Appendix A: Exploring Further

Chapter 11 : Appendix B: Practice

Scan to Download
Chapter 1 Summary : You Don't Know
JS Yet: Scope & Closures

Section Summary

Introduction to This chapter covers how JavaScript determines variable accessibility and the concept of "scope,"
Variables and Scope which governs variable visibility during execution.

About the Book The book, part of the "You Don’t Know JS Yet" series, focuses on scope, function closures, and
module patterns, emphasizing the importance of understanding the parsing and compilation phase of
JS.

Compiled vs. Compilation converts source code to machine instructions in one step, while interpretation runs code
Interpreted line-by-line. Modern JS uses a compiled approach which influences scope management.
Languages

Phases of JS JS programs consist of a Parsing/Compilation phase, creating a map of scopes before execution,
Programs followed by Execution of the compiled code.

Key Observations Errors like syntax and early errors indicate prerequisite parsing. Hoisting behavior (with `var`, `let`,
Supporting Two `const`) also relies on this phase for proper scope resolution.
Phases

Scope Roles: Targets Variables can be assignment targets (receiving values) or sources (providing values). Understanding
vs. Sources these roles helps manage scope effectively.

Cheating with JS scope manipulation techniques (like `eval` and `with`) are discouraged, as they reduce performance
Runtime Scope and readability. Strict mode helps avoid these complications.
Modifications

Lexical Scope JS uses lexical scope, where variable accessibility is determined by code structure. This mapping is
defined during compilation and impacts scope resolution at runtime.

Conclusion The chapter stresses the importance of mastering scope for effective JS programming and sets the
stage for exploring these foundational concepts in subsequent chapters.

Scan to Download
Chapter 1 Summary: What’s the Scope?

Introduction to Variables and Scope

In programming, managing and understanding variables is


fundamental. This chapter delves into how JavaScript (JS)
determines variable accessibility and handles variable
naming. Key concepts include "scope," which is defined as
the rules governing variable visibility and accessibility
during program execution.

About the Book

Welcome to the second book in the "You Don’t Know JS


Yet" series, focusing on the scope system, function closures,
and module patterns in JS. Unlike the common perception of
JS as a purely interpreted language, JS actually involves a
parsing and compilation phase before execution, which is
crucial for understanding scope.

Compiled vs. Interpreted Languages

Scan to Download
-
Compilation:
Involves converting source code into machine instructions in
one step.
-
Interpretation:
Runs code line-by-line, executing each statement
immediately.
Modern JS engines use a combination of both techniques, but
they primarily follow a compiled approach, which affects
how scope is determined and managed.

Phases of JS Programs

JS programs undergo two significant phases:


1.
Parsing/Compilation:
The program is analyzed to create a map of scopes and
variable associations before execution begins.
2.
Execution:
The compiled code is executed, adhering to the previously
established scopes.

Scan to Download
Key Observations Supporting Two Phases

-
Syntax Errors:
Encountered before any code execution, indicating prior
parsing.
-
Early Errors:
Issues like duplicate parameter names throw errors before
execution begins, validating the need for an initial parsing
phase.
-
Hoisting:
The behavior of variables declared with `var`, `let`, and
`const` relies on prior parsing for proper scope resolution.

Scope Roles: Targets vs. Sources

- Variables in a program act as either assignment targets or


value sources.
- Each occurrence of a variable is identified as either a target
(receiving an assigned value) or a source (providing a value).
- Understanding these roles is vital in managing variable
scope effectively.

Scan to Download
Cheating with Runtime Scope Modifications

While JS scope should not be affected during runtime, some


techniques (like `eval` and `with`) can manipulate scopes
dynamically, which is discouraged due to performance and
readability concerns. Using strict mode mitigates the
temptation and complications associated with these
techniques.

Lexical Scope

JS operates under "lexical scope," meaning variable


accessibility is determined by the physical structure of the
code—where functions, blocks, and declarations are placed
in relation to each other. This structural mapping is defined
during the compilation phase, affecting how scopes are
resolved at runtime.

Conclusion

This chapter emphasizes that mastering scope is crucial for


effective JS programming, highlighting the importance of
understanding how code is processed, the nature of variable

Scan to Download
roles, and adopting best practices for code organization. As
the journey through JS continues, the following chapters will
further explore these foundational concepts.

Scan to Download
Example
Key Point:Understanding variable scope is essential
for effective JavaScript programming.
Example:Imagine you're creating a game in JavaScript.
You declare a variable to keep track of the player's score
inside a function. However, if you try to access that
score variable outside of the function, you’ll find that it
is undefined because its scope is limited to within that
function. This illustrates how crucial it is to know where
your variables can be accessed and modified, ensuring
smooth gameplay without unexpected errors.

Scan to Download
Chapter 2 Summary : What’s the Scope?

Chapter 2 Summary: What's the Scope?

Understanding Scope in JS

By the time a programmer has started writing a few


programs, they may become comfortable manipulating
variables. However, it’s crucial to understand how JavaScript
(JS) manages these variables and which are accessible based
on the rules of scope. This chapter delves into scope—the set
of rules governing variable accessibility, especially with
common patterns and pitfalls.

About This Book

Scan to Download
This book focuses on the first fundamental aspect of JS: the
scope system and function closures, which are integral to
module design patterns. While JS is often assumed to operate
in a linear fashion, it actually undergoes a parse/compile
phase before execution, determining variable placement and
access rules.

Compiled vs. Interpreted Languages

The difference between compiled and interpreted


technologies lies in how code is processed. JS is
predominantly a compiled language that utilizes a complex
engine to parse and interpret code into instructions that the
computer can understand, including optimizations for
performance.

Two Phases of Processing

JS programs undergo two main phases—compilation and


execution. During compilation, the program’s structure is
analyzed, variables are scoped, and errors, such as syntax or
early errors, are detected before the code is executed,
ensuring smooth performance.

Scan to Download
Understanding Hoisting

Hoisting refers to the behavior where variable declarations


are processed before their actual execution in the code. JS
engines must understand variable scopes and ensure they are
accessible during runtime. Understanding variations in
variable performance, particularly when using `let` or
`const`, is essential for managing scope effectively.

Runtime Scope Modifications

In non-strict-mode, there are risks of inadvertently modifying


scope at runtime using methods like `eval(..)` or `with`. It's
critical to be aware of these practices as they can lead to
performance issues and obscure readability.

Lexical Scope Defined

Lexical scope determines the visibility and lifetime of


variables based on their position within the nested structure
of code. This chapter emphasizes how scope colors are
assigned to variables, akin to sorting colored marbles into
matching buckets, showing how the JavaScript engine

Scan to Download
understands and processes scopes.

Metaphors for Understanding Scope

Using metaphors such as marbles and buckets or an office


building, the chapter illustrates how scopes are structured and
how variable reference lookups occur, helping to build a
conceptual understanding of access and declaration handling.

Conclusion

Effective understanding of scope in JS requires a mental


model of how declarations work, how variables relate to
scope, and the context of execution. Mastery of these
concepts will improve programming efficacy and clarity. The
next chapter will build on this foundational knowledge by
exploring lexical scope connections in greater detail.

Scan to Download
Chapter 3 Summary : Illustrating
Lexical Scope
Section Key Points

Introduction to Lexical Focuses on lexical scope and scope chain, highlighting variable access during compile time, not
Scope runtime.

Color-Coded Scopes Uses color-coded marbles to represent scopes: RED (global), BLUE (function), GREEN (block),
with upward/outward lookup process explained.

The Lookup Process Variable access generally determined at compile time, optimizing performance; scope latch
predefined during compilation.

Deferred Lookups & Lookups may defer to runtime if variables are undeclared; unresolved references lead to errors.
Scope Reference

Shadowing and Inner scope variables can shadow outer scope variables, making outer variables inaccessible within
Variable Management the shadowing scope.

Tricky Access to Accessing shadowed global variables via the global object is possible but discouraged for clarity
Shadowed Variables and bug prevention.

Illegal Shadowing Strict rules on shadowing: `let` can shadow `var` but not vice versa; improper handling can cause
Instances syntax errors.

Function Names and Functions create identifiers in their scopes, with differences between function declarations and
Scopes expressions noted.

Arrow Functions Arrow functions are anonymous expressions that follow similar scope rules without new behavior
regarding lexical scope.

Conclusion: The Scope Every function initiates a new lexical environment; variable shadowing occurs with reused names,
Chain setting the stage for the next chapter on the global scope.

Chapter 3: The Scope Chain Summary

Introduction to Lexical Scope

Chapter 3 delves into lexical scope, establishing a

Scan to Download
foundational understanding of how variable access works in
JavaScript (JS) through the metaphor of a scope chain. It
emphasizes the importance of clear understanding—seeing
how variable names correspond to their respective scope at
compile time, rather than during runtime.

Color-Coded Scopes

Using the previous chapter's visualizations, different scopes


are represented as color-coded marbles in buckets, where the
colors represent specific scopes:
-
RED
for the global scope.
-
BLUE
for function scopes.
-
GREEN
for block scopes (like loops).
The concept of upward/outward lookup is introduced—a
Install
process Bookey
where App to
the JS engine Unlock
searches Full Text and
for variable
Audio
declarations starting from the current scope until it finds a
match or reaches the global scope.

Scan to Download
Chapter 4 Summary : The Scope Chain

Chapter 4: Around the Global Scope

Importance of Global Scope

- The global scope, while often downplayed due to the


emphasis on functions and modules, remains critical in
JavaScript (JS).
- Understanding the global scope aids in structuring
programs effectively and managing multiple JS files.

Composition of JS Applications

1.
ES Modules
: Used directly with imported references, allowing separate
modules to cooperate.
2.
Bundlers
: Combine multiple files into a single entity for the browser,
necessitating shared naming for access.

Scan to Download
3.
Standalone Scripts
: Individual files can create global variables for cooperation
when lacking an encompassing scope.

Utility of Global Scope

- Global scope houses JS built-ins like primitives (null,


Infinity), natives (Date, Object), global functions (eval,
parseInt), and web API interfaces (navigator, window).
- Both JS and the environment expose globals but should be
managed carefully to avoid clutter.

Location of Global Scope

- The global scope isn't solely the outermost portion of a file;


variations exist across environments.
-
Browser Context
: Top-level variable declarations constitute global variables,
accessible through the global object (window).

Global Variable Handling

Scan to Download
- Shadowing occurs where global properties can be
overridden by local variables.
- Legacy behaviors, like auto-registration of DOM ids as
global variables, create inconsistent global environments.

Unique Global Qualities

- Predefined globals like `[Link]` can behave


unexpectedly when not declared properly.
-
Web Workers
operate in separate threads, providing a clean global
environment but no DOM access.

Console/REPL Environment

- Developer tools emulate global behavior for convenience


but may differ from strict JS specifications, affecting scope
behavior.

ES Module Context

- In ES modules, top-level declarations are module-scoped,

Scan to Download
not global variables. They use imports for cooperation while
retaining access to global identifiers.

Node Environment

- All scripts in Node operate as modules, encapsulating


global context within module scope.
- Actual global variables in Node are added to the global
object using the `global` identifier.

Standard Reference for Global Scope

- `globalThis` (introduced in ES2020) centralizes access to


the global scope across various JS environments, simplifying
management.

Conclusion

- The global scope is vital across JS applications, influencing


multiple interconnected files and environments.
Understanding its nuances can prevent potential pitfalls in
application design and implementation.

Scan to Download
Chapter 5 Summary : Around the Global
Scope

Chapter 5: The (Not So) Secret Lifecycle of


Variables

This chapter delves into the complexities of variable scoping


in JavaScript, specifically focusing on how variables are
declared, hoisted, and how their lifecycle evolves within
different scopes.

When Can I Use a Variable?

- Variables in JavaScript can be accessed after they have been


declared, but a key nuance is that function declarations are
hoisted. This means a function can be called before it is
defined in the code because the JS engine prepares its
reference at the beginning of the scope.
- Hoisting is the concept where variable and function
declarations are moved to the top of their scope during the
compile stage.

Scan to Download
Hoisting: Declaration vs. Expression

- Only function declarations benefit from hoisting, not


function expressions assigned to variables. Consequently,
trying to call a function expression before it’s declared
results in a `TypeError` because the variable exists but is not
functionally initialized.

Variable Hoisting

- Variables declared with `var` are hoisted and initialized to


`undefined`, allowing use before their actual declaration in
the code.
- Hoisting visualizes how the JS engine prepares variables
and functions during the compile stage rather than during
runtime execution.

Re-declaration of Variables

- With `var`, re-declaring a variable does nothing; it's


allowed but effectively treated as a no-operation.
- Using `let` or `const` for a second declaration of the same
variable name within the same scope results in a
`SyntaxError`, preventing re-declaration and promoting

Scan to Download
better programming practices.

Constants and `const` Variables

- Variables declared with `const` must be initialized at the


time of declaration and cannot be re-assigned. Attempting to
re-declare a `const` variable results in an error.
- The restriction on re-declaring `const` variables stems
partly from their requirement to always be initialized.

Loops and Scope Behavior

- The behavior of `let` and `const` in loops demonstrates that


they are not re-declared on subsequent iterations as each loop
iteration creates a new scope.
- However, `const` cannot be used with traditional `for` loops
where the loop variable needs to be reassigned.

Uninitialized Variables (Temporal Dead Zone -


TDZ)

- `let` and `const` variables are hoisted but not initialized,


resulting in a TDZ. You cannot access these variables before
their declaration point in the code, leading to errors.

Scan to Download
Summary of Key Points

- Hoisting allows function declarations to be invoked before


they are defined in code. Variables declared with `var` are
initialized to `undefined` and can be used before their
declaration.
- Re-declaration is permissible with `var` but results in errors
with `let` and `const`.
- Understanding the lifecycle and behavior of variables,
including hoisting, TDZ, and scope, is crucial for mastering
JavaScript scoping.
This chapter prepares the reader to recognize how variable
handling can shape program behavior and reinforces the
necessity of thoughtful design when coding to avoid errors
associated with scope, declaration, and hoisting.

Scan to Download
Chapter 6 Summary : The (Not So)
Secret Lifecycle of Variables

Chapter 6: Limiting Scope Exposure

Introduction

This chapter discusses how to effectively manage variable


scopes in programming, employing principles that minimize
exposure and enhance code organization.

Least Exposure

- Functions define their scopes, while blocks also contribute


to scope creation.
- The principle of Least Exposure (POLE) suggests variables
should be declared only as broadly as necessary to reduce
hazards.

Hazards of Over-Exposing Variables

Scan to Download
1.
Naming Collisions
: Risk of conflicting variable names that can lead to bugs.
2.
Unexpected Behavior
: Exposed variables may be used incorrectly by other code
parts.
3.
Unintended Dependency
: Unnecessarily exposed variables create tight coupling
between code segments, complicating future refactoring.

Example of Applying POLE

- Using the `diff(..)` function, we consider how to limit the


scope of the `tmp` variable to just where it's necessary,
enhancing clarity and reducing potential issues.

Hiding Variables

- Variables can be hidden more effectively using nested


Install
scopes, suchBookey App
as wrapping to Unlock
function Full in
declarations Text and
another
Audio
function (e.g., `hideTheCache()` for caching factorial
calculations).

Scan to Download
Chapter 7 Summary : Limiting Scope
Exposure

Chapter 7: Using Closures

Introduction to Closures

- This chapter focuses on understanding closures, a key


aspect of JavaScript that allows functions to access variables
from outside their own scope.
- Closure builds on the concept of lexical scope, reinforcing
the principle of limiting scope exposure (Least Exposure).

What is Closure?

- Closure refers to the ability of a function to remember and


access its lexical scope even when it is invoked outside that
scope.
- This means that functions can retain access to variables
defined in their enclosing scopes, preserving values that
might otherwise be lost when the outer function executes.

Scan to Download
Example of Closure in Action

- The example of `lookupStudent` illustrates how closures


work. An inner function, `greetStudent`, can access variables
`students` and `studentID` even after `lookupStudent` has
finished executing.
- The inner function retains access to these variables,
preventing them from being garbage collected.

Pointing to Closure

- It's crucial to recognize how arrow functions (like the one in


the `find` method) create their own scope, adding complexity
to closures.

Live Link, Not a Snapshot

- Closure maintains a live link to the variable itself, allowing


updates and reassignments to be reflected in every invocation
of the closure.

Closure Lifecycle and Memory Management

Scan to Download
- A closure remains active as long as there’s at least one
reference to the function.
- Discarding references to closures when they are no longer
needed is vital for memory management to prevent runaway
memory usage.

Closure Example in Event Handling

- When setting up event handlers, closure allows the handler


to maintain context without needing to repeatedly access
DOM elements or attributes during each event firing.

Optimization and Memory Considerations

- It’s advisable to clear references to large variables when


they are no longer necessary to aid garbage collection.

Alternative View of Closure

- Instead of thinking of closure as the ability to link to its


surrounding scope, consider it as a way to keep function
instances alive as long as they are referenced.

Practical Benefits of Closures

Scan to Download
- Improved efficiency by retaining previously computed
values.
- Enhanced readability by encapsulating variables, thus
minimizing scope exposure.

Conclusion

- Closure is an essential tool for writing effective JavaScript


code, affecting performance, readability, and maintainability.
Understanding and using closures wisely can enhance coding
practices significantly.

Scan to Download
Example
Key Point:Understanding closures helps you
encapsulate variables and maintain their state across
invocations.
Example:Imagine you're building a quiz application
where each question should remember the score of the
player. With closures, you can create a function that
increments the score each time the player answers
correctly. Even after that function runs, it keeps a
reference to the score variable so you can access and
update it without needing to redefine or pass it around
repeatedly. This encapsulation not only makes your
code cleaner but also ensures the state is preserved
seamlessly as the quiz progresses.

Scan to Download
Critical Thinking
Key Point:Understanding closures can enhance
JavaScript coding practices significantly.
Critical Interpretation:The chapter emphasizes closures
as a pivotal concept in JavaScript, highlighting their
capability to maintain access to variables in an outer
scope. This can lead to improved efficiency and
readability in code. However, it is essential to approach
this perspective critically. Closures, while powerful, can
also introduce complexity and memory issues if not
managed correctly—an argument supported by
resources like 'JavaScript: The Good Parts' by Douglas
Crockford, which critiques the potential pitfalls of
closures in code maintenance. Therefore, while closures
offer distinct advantages, their usage requires careful
consideration to avoid unintended consequences that
may arise from their inherent features.

Scan to Download
Chapter 8 Summary : Using Closures

Chapter 8: The Module Pattern

Introduction to Modules

In this chapter, we explore the concept of modules, a vital


code organization pattern in programming built upon
previously discussed concepts of lexical scope and closure.
Understanding modules is crucial for structuring code
effectively and managing the visibility of data and functions
(encapsulation).

Encapsulation and Least Exposure (POLE)

Encapsulation refers to bundling related data and functions


that serve a common purpose. It controls visibility, allowing
certain aspects of the encapsulated data to remain private
while exposing others as part of the public API. The Least
Exposure Principle (POLE) encourages guarding against
scope overexposure, leading to better code organization and
maintainability.

Scan to Download
What is a Module?

A module combines related functions and state (data),


featuring a clear delineation between private and public
elements. It maintains state over time, ensuring that
functionality can access and modify this state via its public
API.

Distinction Between Code Patterns

1.
Namespaces
: Simple groupings of stateless functions that lack
encapsulation.
2.
Data Structures
: Groupings of stateful functions without visibility control,
merely data objects.

Classic Module Definition

Classic modules encapsulate data and provide controlled


access through a public API. They are typically defined using

Scan to Download
an Immediately Invoked Function Expression (IIFE) that
keeps variables and functions private, returning an object that
exposes public methods.

Module Factory for Multiple Instances

To create multiple instances of a module, a factory function


can be used instead of an IIFE, allowing for separate states in
each instance. This approach emphasizes the flexibility of
creating new instances as needed.

Classic Module Features

- Outer scope with a function running at least once.


- Hidden information representing module state.
- Function references in the public API that have closure over
internal state.

CommonJS Modules

In [Link], modules are file-based, and each file is treated as


a module. Functions and data inside the module are private
by default, and the public API is defined using
`[Link]`. This style ensures singleton behavior for

Scan to Download
module instances and facilitates easier management of
module dependencies.

Modern ES Modules (ESM)

Similar to CommonJS, ESM modules are file-based and


private by default, but they utilize `import` and `export`
keywords to manage public APIs. ESM inherently applies
strict mode, offering various ways to define exports and
imports.

Closure's Role in Modules

Closures play a crucial role in maintaining module state by


ensuring that public API methods retain access to their
internal state, even when invoked from outside the module.

Conclusion

Modules represent a practical application of lexical scope and


closure principles. They enhance code efficiency and
readability by encapsulating state and behavior while
managing visibility and limiting exposure, ultimately leading
to better structured and organized programs.

Scan to Download
Final Thoughts

Take time to reflect on the concepts of closure and modules,


and practice implementing them in code. This understanding
is foundational for efficient programming and the
construction of scalable applications.

Scan to Download
Chapter 9 Summary : The Module
Pattern

Chapter 9: The Module Pattern

In this chapter, we explore the module pattern, one of the


most important concepts in programming. Modules are built
upon the understanding of lexical scope and closure,
allowing for better code organization and encapsulation.

Encapsulation and Least Exposure (POLE)

Encapsulation is the bundling of data and functions that serve


a common purpose, promoting better organization in code.
The least exposure principle aims to minimize the
accessibility of variables and functions, ensuring that only
necessary parts of the code are public. This enhances code
maintainability and quality.

What Is a Module?

A module is a collection of related data and functions,

Scan to Download
distinguished by its division of private and public details,
known as the public API. Modules maintain state over time
and provide functionality to access and modify that state.

Namespaces (Stateless Grouping)

Namespaces group related functions without data and do not


imply the encapsulation that modules provide. For instance, a
utility object collects stateless functions but lacks the
necessary private data management.

Data Structures (Stateful Grouping)

Data structures can bundle stateful functions and data, but if


they do not implement visibility control, they do not qualify
as true modules.

Modules (Stateful Access Control)

To qualify as a module, an implementation must ensure both


data encapsulation and access control. For example, the
Install
classic Bookey
module patternApp toIIFE
uses an Unlock Full
to create Text and
a scope,
Audio
returning an object that serves as the public API while
keeping the internal data private.

Scan to Download
Chapter 10 Summary : Appendix A:
Exploring Further

Summary of Chapter 10: Exploring Further

Overview

This chapter delves into more nuanced aspects related to


topics previously discussed, providing optional material for
those interested in deeper understanding. It emphasizes the
importance of knowledge over superficial understanding,
preparing developers for unexpected challenges in coding.

Implied Scopes

-
Parameter Scope
: Function parameters can create unexpected scopes,
especially with non-simple parameters (default values, rest
parameters, destructured parameters). Example code
illustrates how parameter lists can have distinct scopes that

Scan to Download
alter behavior and lead to errors, such as Temporal Dead
Zone (TDZ) issues.
-
Function Name Scope
: The name of a function expression exists in its own separate
scope, demonstrating that scope rules can lead to confusion if
not recognized. Shadowing identifiers is permissible but can
have significant implications.

Named vs. Anonymous Functions

- Functions should be named to aid in clarity and


debuggability. Named functions help in stack traces and
improve comprehension for future readers of code.
- Relying on inferred names from anonymous functions can
be misleading, as many anonymous functions do not have a
name that might be useful during debugging.
- The chapter strongly advocates that all functions should
have explicit names for clarity and maintainability.

Arrow Functions

- Arrow functions are always anonymous, offering less


clarity compared to named functions.

Scan to Download
- While they have advantages, such as lexical scoping of
`this`, their use should be limited to specific cases due to the
trade-off on readability.

IIFE Variations

- Immediately Invoked Function Expressions (IIFEs) should


also be named, similar to regular functions. This practice
improves understanding of their purpose and functionality.

Hoisting and Its Benefits

- Hoisting allows function declarations to be accessible


before their definition, promoting a top-down reading of
code, which can improve clarity and maintainability.
- The discussion acknowledges variable hoisting (specifically
with `var`) but mentions its potential pitfalls, emphasizing
that awareness and careful structure can mitigate issues.

Discussion on `var`, `let`, and `const`

- While `var` is often criticized, it still has valid use cases,


especially in function scope. The use of `let` for block scope
is endorsed, but the advantages of `var` should not be

Scan to Download
discarded.
- The author addresses common misconceptions regarding
`const`, arguing that it can lead to misunderstandings about
immutability.

Conclusion

The chapter encourages developers to master and utilize the


full breadth of JavaScript's features, including variable
declarations and function naming, to produce clearer, more
maintainable code.

Scan to Download
Chapter 11 Summary : Appendix B:
Practice

Chapter 11: Practice

This chapter presents exercises to enhance and test your


understanding of key concepts discussed in the book. It
encourages you to attempt the exercises independently before
reviewing the provided solutions.

Buckets of Marbles

-
Objective:
Write a program using nested functions and block scopes
with specific constraints:
- Use at least six colors to denote different scopes.
- Include two function scopes and two block scopes.
- Shadow at least one variable.
- Ensure at least one variable reference resolves to a
declaration two levels up the scope chain.

Scan to Download
Closure Exercises

1.
Part 1:

- Implement `isPrime(v)` to determine if a number is prime.


- Create `factorize(v)` to generate a list of prime factors for
a number.
- Use closure to cache results to improve performance.
2.
Part 2:

- Create a `toggle(..)` function that alternates through


provided values each time it is called.
3.
Part 3:

- Build a basic calculator with a `calculator()` function that


handles digit inputs and arithmetic operations (`+`, `-`, `*`,
`/`) in sequential order.
- Implement a helper function `useCalc(calc, keys)` to
simulate key presses.

Modules Exercise

Scan to Download
- Convert the calculator from Closure Part 3 into a module
pattern to enable creating multiple calculator instances. This
requires changing the interface to include methods like
`number(..)`, `plus()`, `minus()`, `mult()`, `div()`, and `eq()`.

Suggested Solutions

- Solutions to exercises are provided for comparison but


emphasize that there are multiple approaches and styles to
achieve the same outcomes.
This chapter concludes with an invitation to continue to the
next book, which will delve into Objects and Classes, further
expanding your JavaScript knowledge.

Scan to Download
Best Quotes from You Don't Know JS
Yet by Kyle Simpson with Page Numbers
View on Bookey Website and Generate Beautiful Quote Images

Chapter 1 | Quotes From Pages 1-113


[Link] don’t finish knowing everything about JS, you
just keep learning more and more as you spend
more time with the language.
[Link] mission with YDKJSY is to empower every single JS
developer to fully own the code they write, to understand it
and to write with intention and clarity.
[Link] primary point of the title 'You Don’t Know JS Yet' is to
point out that most JS developers don’t take the time to
really understand how the code that they write works.
[Link] you place a variable declaration inside a function, the
compiler handles this declaration as it’s parsing the
function, and associates that declaration with the function’s
scope.
5.I added 'Yet' to the title, not only because it’s the second
edition, but because ultimately I want these books to

Scan to Download
challenge you in a hopeful rather than discouraging way.
Chapter 2 | Quotes From Pages 114-322
[Link] we rely on guesses and intuition, we may
accidentally get the right answers some of the time,
but many other times we’re far off. This isn’t a
recipe for success.
[Link] need to build accurate and helpful mental models as
foundation moving forward.
[Link] term 'lexical' refers to the first stage of compilation
(lexing/parsing).
[Link] determination of colored buckets, and the marbles they
contain, happens during compilation.
[Link] Engine exhausts all lexically available scopes and
still cannot resolve the lookup of an identifier, an error
condition then exists.
[Link] strict-mode, the Global Scope Manager would instead
have responded: 'Nope, never heard of it. Sorry, I’ve got to
throw a ReferenceError.'
Chapter 3 | Quotes From Pages 323-480

Scan to Download
[Link] we rely on guesses and intuition, we may
accidentally get the right answers some of the time,
but many other times we’re far off.
[Link] need to build accurate and helpful mental models as
foundation moving forward.
[Link] are declared in specific scopes, which can be
thought of as colored marbles from matching-color
buckets.
[Link] with it, though, because these discussions really
hammer home just how much we all don’t know about
scope, yet.
[Link] occurs, which prevents access to the outer
variable from that point inward.
[Link] rely on accidental global variables. Always use
strict-mode, and always formally declare your variables.

Scan to Download
Chapter 4 | Quotes From Pages 481-661
[Link] if you need to maintain two or more variables
of the same name, you must use separate (often
nested) scopes.
[Link] the need for a runtime lookup is a key
optimization benefit of lexical scope.
[Link]: just because you can doesn’t mean you should.
[Link] global scope is present and relevant in every JS
program, even though modern patterns for organizing code
into modules de-emphasizes much of the reliance on
storing identifiers in that namespace.
[Link] positioning of scopes nested inside one another creates
a natural scope hierarchy throughout the program, called
the scope chain.
Chapter 5 | Quotes From Pages 662-892
[Link] global scope of a JS program is a rich topic,
with much more utility and nuance than you
would likely assume.
[Link] developers agree that the global scope shouldn’t just

Scan to Download
be a dumping ground for every variable in your application.
3.A repeated var declaration of the same identifier name in a
scope is effectively a do-nothing operation.
[Link]’s try this: studentName = "Suzy"; // ReferenceError
[Link](studentName); let studentName;
[Link] both cases, a SyntaxError is thrown on the second
declaration.
[Link] TDZ is the time window where a variable exists but is
still uninitialized, and therefore cannot be accessed in any
way.
7.I assert that hoisting should be used to refer to the
compile-time operation of generating runtime instructions
for the automatic registration of a variable at the beginning
of its scope, each time that scope is entered.
Chapter 6 | Quotes From Pages 893-1218
[Link] essentially says, default to exposing the bare
minimum necessary, keeping everything else as
private as possible.
[Link] TDZ (temporal dead zone) error is strange and

Scan to Download
frustrating when encountered. Fortunately, TDZ is
relatively straightforward to avoid if you’re always careful
to place let/const declarations at the top of any scope.
[Link] you decide initially that a variable should be
block-scoped, and later realize it needs to be elevated to be
function-scoped, then that dictates a change not only in the
location of that variable’s declaration, but also the
declarator keyword used.
[Link] only practical answer to avoiding the vagaries of FiB is
to simply avoid FiB entirely. In other words, never place a
function declaration directly inside any block.
[Link] variables in as small and deeply nested of scopes
as possible, rather than placing everything in the global (or
even outer function) scope.

Scan to Download
Chapter 7 | Quotes From Pages 1219-1571
[Link], as applied to variable/function scoping,
essentially says, default to exposing the bare
minimum necessary, keeping everything else as
private as possible.
[Link] allows greetStudent(..) to continue to access those
outer variables even after the outer scope is finished (when
each call to lookupStudent(..) completes).
[Link] is observed when a function uses variable(s) from
outer scope(s) even while running in a scope where those
variable(s) wouldn’t be accessible.
[Link] can improve code readability, bounding
scope-exposure by encapsulating variable(s) inside
function instances, while still making sure the information
in those variables is accessible for future use.
[Link] is actually a live link, preserving access to the full
variable itself. We’re not limited to merely reading a value;
the closed-over variable can be updated (re-assigned) as
well!

Scan to Download
Chapter 8 | Quotes From Pages 1572-2025
[Link] is observed when a function uses
variable(s) from outer scope(s) even while running
in a scope where those variable(s) wouldn’t be
accessible.
[Link] allows greetStudent(..) to continue to access those
outer variables even after the outer scope is finished.
[Link] can improve efficiency by allowing a function
instance to remember previously determined information
instead of having to compute it each time.
[Link] resultant narrower, more specialized function instances
are cleaner to interact with, since the preserved information
doesn’t need to be passed in every invocation.
[Link] idea is to group alike program bits together, and
selectively limit programmatic access to the parts we
consider private details.
[Link] is actually a live link, preserving access to the full
variable itself.
[Link]’s important to know where closures appear in our

Scan to Download
programs, and what variables are included.
Chapter 9 | Quotes From Pages 2026-2274
[Link] a moment to reflect on how far you’ve come
in this journey so far; you’ve taken big steps in
getting to know JS more deeply!
[Link] central theme of this book has been that understanding
and mastering scope and closure is key in properly
structuring and organizing our code.
[Link] idea is to group alike program bits together, and
selectively limit programmatic access to the parts we
consider private details.
[Link] are one of the most effective ways to structure and
organize your program’s functionality and data.
[Link] is the defensive private by default posture we always
take, making sure we avoid over-exposure and interact only
with the minimal public API surface area necessary.
[Link] magic of how all our module state is maintained is
closures leveraging the lexical scope system.
[Link]’s a really good idea to pause, reflect, and practice what

Scan to Download
we’ve just discussed.

Scan to Download
Chapter 10 | Quotes From Pages 2275-3206
1.I believe it’s better to be empowered by knowledge
of how things work than to just gloss over details
with assumptions and lack of curiosity.
[Link]’t you rather be prepared for the inevitable bumps
of off-roading?
[Link] only excuse for not including a name on a function is
either laziness (don’t want to type a few extra characters)
or uncreativity (can’t come up with a good name).
[Link] functions need names. Every single one. No exceptions.
Chapter 11 | Quotes From Pages 3207-3426
[Link] exercise doesn’t have a specific right answer
that you have to get exactly. Your approach may
differ some (or a lot!) from the solutions presented,
and that’s OK.
[Link] you’re happy with your code, I am, too!
[Link] trade-off is memory. We’re essentially growing our
cache (in memory) unboundedly.
[Link] most every call will have a unique input, and the cache is

Scan to Download
essentially never used to any benefit, this is an
inappropriate technique to employ.
[Link] the underlying call, first check the cache, and if a result
is already known, return.

Scan to Download
You Don't Know JS Yet Questions
View on Bookey Website

Chapter 1 | You Don't Know JS Yet: Scope &


Closures| Q&A
[Link]
What is the significance of understanding scope in
JavaScript?
Answer:Understanding scope is crucial in
JavaScript because it defines the accessibility of
variables within your code. It determines which
variables can be accessed at any point in the
program, thus preventing potential conflicts,
especially when two variables share the same name
but exist in different scopes. It helps developers
write more predictable and clearer code.

[Link]
How does JavaScript handle variable accessibility?
Answer:JavaScript determines variable accessibility through
a well-defined set of rules known as scope. Variables

Scan to Download
declared within a specific block or function can only be
accessed within that same block or function unless they are
declared in a higher scope.

[Link]
Why is the title 'You Don’t Know JS Yet' important?
Answer:The title emphasizes that learning JavaScript is an
ongoing journey. It encourages developers to remain curious,
to challenge their assumptions, and to deepen their
understanding of the language over time, recognizing that
mastery is a process rather than a destination.

[Link]
What is the relationship between compilation and
execution in JavaScript?
Answer:JavaScript programs undergo a two-phase process:
first, the parsing and compilation phase, where the code
structure is analyzed and prepared, followed by the execution
phase, where the actual code runs. This separation is key to
understanding how scope is determined and how errors can
surface during code execution.

Scan to Download
[Link]
What is 'lexical scope', and why is it important?
Answer:Lexical scope refers to the visibility of variables in
relation to their placement in your code. It is determined at
compile time and is critical to understand, as it dictates how
variables are accessed and ensures that each variable or
function can be properly scoped to prevent naming conflicts.

[Link]
How can understanding scope improve coding practices?
Answer:By grasping scope, developers can avoid pitfalls like
variable conflicts, enhance code readability, and manage
memory more effectively. It empowers developers to write
more modular, maintainable code, reducing bugs associated
with variable accessibility.

[Link]
What are closures, and why are they significant?
Answer:Closures are functions that remember the scope in
which they were created, allowing them to access variables
from that scope even when invoked outside their original

Scan to Download
context. They are significant because they enable data
encapsulation and create private variables, which are
fundamental for module patterns in JavaScript.

[Link]
How does JavaScript handle errors during execution?
Answer:JavaScript can identify syntax errors, early errors,
and logical errors during the compilation phase before
execution begins. This means that any issues in the code,
including those that don't relate directly to the lines currently
being executed, can prevent the program from running
altogether.

[Link]
What are the best practices for learning JavaScript as
outlined in the book?
Answer:Best practices include taking time to digest each
chapter thoroughly, practicing concepts and code
continuously, engaging in discussions with peers, and
approaching learning as a process of exploration rather than
rushing through material.

Scan to Download
[Link]
What is the impact of using eval() and with in
JavaScript?
Answer:Using eval() and with can modify the scope at
runtime, leading to unexpected behavior and security risks.
They are generally discouraged as they compromise code
clarity and could hinder performance. It's recommended to
use strict-mode to avoid these issues.
Chapter 2 | What’s the Scope?| Q&A
[Link]
What is the main concept introduced in Chapter 2
regarding how JavaScript manages variables?
Answer:The main concept introduced is 'lexical
scope', which determines which variables are
accessible based on where they are declared in
relation to each other in the code.

[Link]
How are variables identified during the compilation
phase in JavaScript?
Answer:Variables are identified during the compilation phase

Scan to Download
through a structured process that involves tokenizing, parsing
(which generates an Abstract Syntax Tree), and code
generation. This helps the scope manager map out variable
accessibility.

[Link]
What metaphor is used to explain the concept of scope?
Answer:The chapter uses the metaphor of sorting colored
marbles into color-coded buckets, where marbles represent
variables and buckets represent scopes. Different colored
scopes determine which marbles (variables) are accessible
based on where they were originally created.

[Link]
How does the conversation model between the Engine and
the Scope Manager aid understanding JavaScript
execution?
Answer:This model illustrates how the Engine in JavaScript
asks the Scope Manager about variables during both
compilation and execution. It helps to conceptualize how
variable declarations are handled and how scope lookups are

Scan to Download
performed.

[Link]
What drama could occur if strict-mode is not used during
variable declarations?
Answer:Without strict-mode, JavaScript can accidentally
create global variables when trying to assign a value to an
undeclared variable, leading to potential bugs and confusing
behavior.

[Link]
What key takeaway does the chapter suggest regarding
the use of strict-mode?
Answer:Always use strict-mode as it prevents accidental
global variable creation and helps raise errors for undeclared
variables, thus maintaining a cleaner and more predictable
codebase.

[Link]
How is hoisting described in the context of variable
declaration and scope?
Answer:Hoisting is described as a mechanism where variable
declarations are processed before execution begins, meaning

Scan to Download
that variables are recognized within their scope even before
their actual declaration appears in the code.

[Link]
How does the chapter propose to visualize nested scopes?
Answer:Nested scopes can be visualized using the metaphor
of an office building, where each floor represents a scope.
Variables are looked up starting from the current floor and
moving up to the global scope if not found.

[Link]
Why is it important for programmers to understand how
scopes work in JavaScript?
Answer:Understanding how scopes work allows
programmers to create predictable, bug-free code with a clear
structure, preventing conflicts and errors caused by variable
accessibility.

[Link]
What should programmers practice to strengthen their
understanding of scope in JavaScript?
Answer:Programmers should practice by going through their
code aloud, simulating conversations between the Engine and

Scan to Download
Scope Managers to clarify their understanding of variable
scope and accessibility.
Chapter 3 | Illustrating Lexical Scope| Q&A
[Link]
What is lexical scope and why is it important in
JavaScript?
Answer:Lexical scope refers to the visibility of
variables based on their placement in the code or
tree structure during the compilation. It is
important because it determines how variable names
are resolved, preventing naming conflicts and
ensuring that functions reference the correct
variables depending on where they are defined.

[Link]
How can you visualize the concept of scope in JavaScript?
Answer:One effective metaphor is to think of scope as
colored marbles sorted into buckets. Each variable (marble)
is assigned to a scope (bucket) during declaration, and this
color helps determine which variable is accessed when

Scan to Download
referenced in nested scopes.

[Link]
Explain the idea of shadowing in scope. How does it affect
variable access?
Answer:Shadowing occurs when a variable in an inner scope
has the same name as a variable in an outer scope. The inner
variable 'shadows' the outer one, meaning that within the
inner scope, references to that variable name will refer to the
inner variable, not the outer one, effectively blocking access
to the outer variable.

[Link]
What are ‘lookup failures’ in JavaScript’s variable
resolution process?
Answer:Lookup failures happen when the JavaScript engine
cannot find a variable in the current scope or any of the
parent scopes, leading to a reference error. This can happen if
a variable is undeclared or if it is being accessed from a
scope where it is not visible.

[Link]
How do nested scopes relate to the scope chain?

Scan to Download
Answer:Nested scopes create a chain of scopes (the scope
chain), which defines how variable access works. When a
variable is referenced, the JavaScript engine starts at the
innermost scope and moves outward through the nested
scopes in search of the variable until it finds a match or
exhausts all options.

[Link]
What is the significance of using strict mode in relation to
scope and variables?
Answer:Strict mode enforces more secure coding practices
by preventing certain actions, such as creating global
variables accidentally or assigning to undeclared variables.
This helps catch errors at compile-time, making the code
more predictable and avoid potential bugs.

[Link]
In what ways can function declarations and expressions
differ in handling scope?
Answer:Function declarations are hoisted, meaning their
names are accessible within the scope before they are

Scan to Download
executed, while function expressions create identifiers only
when executed, making them unavailable until that point.
Additionally, named function expressions provide lexical
names but do not hoist like declarations.

[Link]
Describe how arrow functions behave in terms of scope
compared to traditional function declarations/expression.
Answer:Arrow functions maintain the lexical context from
which they were defined, inheriting the 'this' value from their
surrounding scope, unlike traditional functions that define
their own 'this' value. However, both types adhere to the rules
of lexical scoping in terms of variable visibility.

Scan to Download
Chapter 4 | The Scope Chain| Q&A
[Link]
What is lexical scope and why is it useful to understand?
Answer:Lexical scope refers to the scope of
variables defined by where they are declared in the
source code. Essentially, functions and variables are
accessible based on their position in the code.
Understanding lexical scope is crucial since it
governs how variables are resolved during
execution, allowing developers to manage variable
visibility and prevent conflicts across different
scopes.

[Link]
How does the scope chain function in JavaScript?
Answer:The scope chain in JavaScript determines how
variable lookups occur, starting from the current scope and
moving outward to parent scopes until the variable is found
or the global scope is reached. This means if a variable is not
found in the current scope, JavaScript checks the parent

Scan to Download
scope and continues outward, stopping at the first match.

[Link]
What is the difference between a global variable and a
variable defined in a function?
Answer:A global variable is available throughout the entire
program, while a variable defined within a function is only
accessible within that function's scope. This encapsulation
allows developers to create private variables while still
having global variables for broader usage.

[Link]
What does shadowing mean in the context of variable
scope?
Answer:Shadowing occurs when a variable defined in a
narrower scope has the same name as a variable in an outer
scope. The inner variable 'shadows' or hides the outer
variable, meaning that within the inner scope, any reference
to that variable name will refer to the inner variable.

[Link]
How can global variables lead to potential conflicts in a
program?

Scan to Download
Answer:Global variables can create conflicts when multiple
scripts introduce variables with the same name, leading to
unexpected behaviors and bugs. Avoiding the use of global
variables or carefully managing them is crucial to
maintaining the integrity of a program.

[Link]
What is the importance of the global scope in modern
JavaScript applications?
Answer:The global scope remains crucial because it serves as
an interface for globally accessible functions and objects,
such as built-in JavaScript globals or third-party libraries.
Understanding and managing the global scope can improve
program organization and avoid naming conflicts.

[Link]
How does defining a global variable in a module differ
from doing so in a traditional JS file?
Answer:In a module, variables defined at the top level are not
added to the global scope; they are instead scoped to the
module itself. This means they cannot be accessed as global

Scan to Download
variables unless explicitly exported, unlike variables defined
in a traditional script, which automatically become global if
declared at the top level.

[Link]
Why is it advised to use 'var' for declaring global
variables?
Answer:Using 'var' for global declarations ensures that the
variable becomes a property of the global object, avoiding
conflicts with lexical scoping rules for 'let' and 'const' which
do not create global object properties. This practice helps to
maintain clarity and predictability in the code.

[Link]
What changes were introduced to global scoping with
ES2020?
Answer:ES2020 introduced 'globalThis', a standardized way
to reference the global scope across different environments
(browser, [Link], etc.). This simplifies the process of
accessing global variables and functions without worrying
about the environment specifics.

Scan to Download
[Link]
What are some common pitfalls developers face
regarding the global scope?
Answer:Common pitfalls include accidentally shadowing
global variables with local declarations, incorrectly assuming
variables are globally available due to module usage, and
relying on browser-specific behaviors in different JS
environments. Awareness of these issues is essential for
writing robust JavaScript code.
Chapter 5 | Around the Global Scope| Q&A
[Link]
Why is understanding the global scope important in
JavaScript programming?
Answer:Understanding the global scope is critical
for mastering JavaScript because it serves as the
foundational context in which all code runs. It
provides visibility and access to built-in functions
and objects, ensuring that developers can effectively
manage their code across multiple files and modules.

Scan to Download
Moreover, recognizing how the global scope works
in various environments (like browsers vs. [Link])
aids in avoiding common pitfalls such as variable
shadowing and unintended overwrites.

[Link]
What does hoisting mean in the context of JavaScript?
Answer:Hoisting refers to the JavaScript mechanism where
variable and function declarations are moved to the top of
their respective scopes during the compilation phase,
allowing for reference to them even before their actual
declaration in the code. This means you can call functions or
use variables before they appear to be defined.

[Link]
What is the difference between function declarations and
function expressions regarding hoisting?
Answer:Function declarations are fully hoisted, meaning they
can be invoked before their declaration in the code due to
their entire function reference being made available at the top
of the scope. In contrast, function expressions, such as those

Scan to Download
assigned to a variable, are only hoisted with their variable
name but not initialized, which leads to a TypeError if called
before their assignment.

[Link]
How do let and const declarations differ from var
declarations in terms of scope and initialization?
Answer:While let and const declarations are hoisted just like
var declarations, they introduce a concept called the
Temporal Dead Zone (TDZ). This means that they are not
accessible until the line of code where they were declared is
executed, preventing runtime errors caused by early access.
Additionally, const requires initialization upon declaration,
whereas let can be declared without initialization but still has
TDZ restrictions.

[Link]
What are the implications of shadowing in JavaScript
variable declarations?
Answer:Shadowing occurs when a variable in an inner scope
uses the same name as a variable in an outer scope, leading

Scan to Download
the inner variable to override or 'shadow' the outer one. This
can create confusion and bugs in code, making it important
for developers to be aware of the scoping rules to prevent
unintended consequences.

[Link]
What happens if you attempt to redeclare a variable with
let or const in the same scope?
Answer:Attempting to redeclare a variable using let or const
in the same scope will throw a SyntaxError. This is because
both let and const disallow redeclaration of the same
identifier within a scope, contrasting with var, which allows
it without any error.

[Link]
Can you encounter Temporal Dead Zone (TDZ) errors
with variables declared using var?
Answer:No, TDZ errors are specific to variables declared
with let and const. Variables declared using var are initialized
to undefined at the start of their scope, preventing TDZ errors
as they can be accessed even before their declaration, albeit

Scan to Download
returning 'undefined' until initialized.

[Link]
What is globalThis, and why is it significant in the context
of global scope?
Answer:GlobalThis is a standardized reference to the global
scope object that can be used consistently across different
JavaScript environments (like browsers and [Link]). It
eliminates the need for environment-specific global
references such as window, self, or global, providing a
uniform way to access the global object and enhancing code
portability.
Chapter 6 | The (Not So) Secret Lifecycle of
Variables| Q&A
[Link]
What is hoisting in JavaScript?
Answer:Hoisting is a JavaScript mechanism where
variables and function declarations are moved to the
top of their respective scopes during the compile
phase. This means that you can use variables and
call functions even before they are declared in the

Scan to Download
code.

[Link]
How does function hoisting differ from variable hoisting?
Answer:Function hoisting refers to the fact that function
declarations are fully hoisted and can be invoked before they
are defined, whereas variable hoisting only registers the
variable name at the top of its scope and initializes it to
'undefined' until the actual assignment is encountered.

[Link]
What is the Temporal Dead Zone (TDZ)?
Answer:TDZ is a term that describes the time period from
when a variable is hoisted but not yet initialized (particularly
for 'let' and 'const' declarations). During this period,
referencing the variable will result in a ReferenceError.

[Link]
Why should variable declarations be scoped as narrowly
as possible?
Answer:Narrow scoping of variable declarations minimizes
exposure, reducing risks such as naming collisions,
unexpected behavior, and unintended dependencies in your

Scan to Download
program.

[Link]
What happens when a variable is declared multiple times
using 'var' in the same scope?
Answer:Re-declaring a variable with 'var' in the same scope
does nothing; it effectively becomes a no-op since the
variable is already registered. The last assignment to the
variable prevails, but no errors are thrown.

[Link]
What error occurs when attempting to re-declare a
variable with 'let' or 'const' in the same scope?
Answer:Attempting to re-declare a variable using 'let' or
'const' within the same scope will throw a SyntaxError,
indicating that the identifier has already been declared.

[Link]
How can you prevent TDZ errors when using 'let' and
'const'?
Answer:To avoid TDZ errors, it is recommended to always
place 'let' and 'const' declarations at the top of their respective
scopes.

Scan to Download
[Link]
What is the Principle of Least Exposure (POLE)?
Answer:POLE is a software engineering principle that
emphasizes minimizing the exposure of variables and
functions in a program. By keeping variables private and
constraining access to them, you can create more secure and
maintainable code.

[Link]
Why should functions not be defined inside blocks?
Answer:Defining functions inside blocks can lead to
unpredictable behavior due to differences in how various
JavaScript environments handle function declarations. It’s
safer to define functions at the top level of a scope.

[Link]
What is an Immediately Invoked Function Expression
(IIFE)?
Answer:An IIFE is a function expression that is executed as
soon as it is defined. This pattern allows you to create a
scope to hide variables and avoid polluting the global scope.

Scan to Download
Chapter 7 | Limiting Scope Exposure| Q&A
[Link]
What is the Principle of Least Exposure (POLE)?
Answer:POLE suggests that we should minimize the
exposure of variables in our programs by keeping
them in the smallest and most appropriate scope.
This helps to avoid hazards like naming collisions,
unexpected behavior due to unintended access, and
unintended dependencies that could complicate
future code maintenance.

[Link]
How does closure leverage scope to improve code
structure?
Answer:Closure allows functions to retain access to their
lexical scope even after that function has finished executing.
This means we can create functions that can remember
variables from their surrounding context, thus keeping them
organized and minimizing unnecessary global variable usage.

[Link]
Can you provide an example of closure in use?

Scan to Download
Answer:Yes, consider a function `lookupStudent(studentID)`
that returns an inner function `greetStudent(greeting)`. The
inner function accesses `studentID` and other variables from
its enclosing function. When called later, `greetStudent` can
still use `studentID`, demonstrating closure by maintaining
access to that variable.

[Link]
What are common pitfalls regarding closures that
developers should be aware of?
Answer:Developers often mistakenly believe closure holds a
snapshot of a variable's value at the time the closure is
created. Instead, closure maintains a reference to the variable,
meaning any changes to the variable will be reflected when
the closure is executed. This confusion is especially common
in loops where variables are closed over.

[Link]
What are the benefits of using closures in programming?
Answer:Closures can enhance efficiency by allowing
functions to remember previously computed values,

Scan to Download
improving readability by encapsulating related variables, and
enabling more flexible code structures by maintaining the
relevant context without exposing it globally.

[Link]
How can memory management be improved when using
closures?
Answer:To manage memory better, if a variable is no longer
needed but is held by a closure, it’s good practice to
explicitly set that variable to `null` or remove it from
closures to allow for garbage collection, thus preventing
memory leaks.

[Link]
What should developers avoid when working with
function declarations inside loops?
Answer:Developers must avoid using var for loop counters in
closures because they create only one variable instance
shared across iterations. Instead, using let for the loop
counter ensures each iteration has its own unique instance
captured in closure.

Scan to Download
[Link]
How does the behavior of closures change in event
handling?
Answer:Event handlers often use closure to retain access to
variables from the outer scope when the callback is invoked.
This means that even if the outer function has completed, the
event handler can still access the values it closed over,
allowing for more dynamic and contextually aware behavior.

[Link]
In what context should function declarations not be used?
Answer:Function declarations should not be used inside
blocks (like if statements) due to inconsistent behavior across
different JavaScript environments. Instead, they should be
defined at the top level to avoid confusion and ensure
predictable behavior.
Chapter 8 | Using Closures| Q&A
[Link]
What is closure in programming?
Answer:Closure is observed when a function retains
access to its lexical scope, allowing it to use outer

Scan to Download
variables even when invoked outside that scope. It
results in the ability for a function to access
variables from its enclosing scope after the outer
function has executed.

[Link]
Why is closure important in JavaScript?
Answer:Closure is essential in JavaScript for managing
variable scope and state in function contexts. It allows
developers to create private variables, maintaining state
across function calls and implementing functional
programming techniques like callbacks and partial
application.

[Link]
Can you explain the 'least exposure principle' (POLE)?
Answer:The least exposure principle encourages developers
to limit the accessibility of variables to prevent unintended
access and modifications. By encapsulating variables within
functions or blocks, we maintain cleaner and more
maintainable code.

Scan to Download
[Link]
How does closure relate to memory management?
Answer:Closure can prevent memory from being collected
by the garbage collector because the closed-over variables
are retained in memory as long as references to the closures
remain. This can lead to increased memory usage, hence it's
crucial to manage closures and release them when no longer
needed.

[Link]
What is the difference between a module and a
namespace?
Answer:A module encapsulates related data and methods,
providing a public API while keeping certain elements
private, thus controlling visibility. On the other hand, a
namespace merely groups a collection of related functions
without the level of encapsulation, meaning all internal data
is publicly accessible.

[Link]
How do we create a module in JavaScript?
Answer:Modules can be created using the module pattern,

Scan to Download
often involving an immediately invoked function expression
(IIFE) that returns an object containing references to public
methods. This allows certain data to remain private while
exposing controlled functionalities.

[Link]
What is a classic module pattern?
Answer:The classic module pattern involves defining a
function (often an IIFE) that contains private variables and
functions. It returns an object that acts as a public API,
allowing controlled access to the internal variables through
methods defined within that IIFE.

[Link]
How can we optimize closure-related memory usage?
Answer:We can optimize memory usage by ensuring that
unused references are discarded. This includes cleaning up
closure references when they are no longer needed,
particularly in event handlers or when managing stateful
modules.

[Link]
What are common uses of closures in JavaScript?

Scan to Download
Answer:Common uses of closures in JavaScript include
callback functions in asynchronous operations (like Ajax
calls), event handler functions, and encapsulating private
state within modules.

[Link]
Explain how closures can help improve code readability.
Answer:Closures allow for the encapsulation of related
functionality and state, leading to better-organized code.
They limit variable exposure, making it clear which parts of
the code interact with which data, thus enhancing
maintainability and understanding of the code structure.
Chapter 9 | The Module Pattern| Q&A
[Link]
What is a module in JavaScript?
Answer:A module is a collection of related data and
functions, characterized by a division between
hidden private details and public accessible details,
usually called the 'public API.' It is stateful,
maintaining information over time and providing

Scan to Download
functionality to access and update that information.

[Link]
Why is encapsulation important in programming?
Answer:Encapsulation is important as it helps bundle related
information (data) and behavior (functions) together,
allowing for better organization, limiting access to the
internal state, reducing the risk of unintended interactions,
and improving maintainability of the software.

[Link]
What does POLE stand for and why is it important?
Answer:POLE stands for 'Private by default, Only expose
what is necessary.' This principle emphasizes limiting access
to private details in order to protect against scope
over-exposure, which helps in maintaining better code
organization and overall quality.

[Link]
What are the differences between a module and a
namespace?
Answer:A module contains both stateful data and functions
with access control (public API and private details), while a

Scan to Download
namespace is a simple grouping of stateless functions
without any encapsulation or state management.

[Link]
How does the IIFE (Immediately Invoked Function
Expression) relate to modules?
Answer:An IIFE is often used to create a module by defining
an outer scope that encapsulates private variables and
exposes a public API. This allows the module's internal state
to remain private while offering specific methods to interact
with that state.

[Link]
What is the significance of using closures in modules?
Answer:Closures allow an inner function to access variables
from its outer scope even after that outer scope's execution
context has completed, enabling persistent access to private
state throughout the life of a module.

[Link]
What is the Node CommonJS module format?
Answer:The Node CommonJS module format is a file-based
system where each module resides in its own file. This

Scan to Download
format uses '[Link]' to expose public API methods
and 'require()' to import other modules.

[Link]
Can you explain the differences between CommonJS and
ESM (ES Modules)?
Answer:CommonJS modules are loaded synchronously and
allow only one export object, while ESM allows
asynchronous loading, can export multiple named members
or a single default, and uses 'import' and 'export' keywords
instead of 'require()' and '[Link]'.

[Link]
Why is function hoisting in JavaScript beneficial?
Answer:Function hoisting allows the function declaration to
be accessible before its definition in the code. This makes it
easier to organize the code so that executable calls are at the
top, leading to clearer code structure.

[Link]
How should functions be named in JavaScript for better
code quality?
Answer:Functions should always be named, even anonymous

Scan to Download
functions, to improve readability, aid debugging by
providing meaningful context in stack traces, and ensure
self-referential capabilities where needed.

Scan to Download
Chapter 10 | Appendix A: Exploring Further| Q&A
[Link]
Why is it important to understand the nuances of
JavaScript functions and their scopes?
Answer:Understanding the nuances of JavaScript
functions and their scopes is crucial because it
empowers developers to avoid common pitfalls that
can lead to bugs and unexpected behavior in their
code. By recognizing how scopes are created and
where variables are accessible, developers can write
clearer, more efficient, and maintainable code.

[Link]
What are the two types of functions mentioned in the
chapter?
Answer:The two types of functions are anonymous functions
and named functions. The chapter emphasizes the importance
of using named functions for better readability and
debugging.

[Link]
What are the implications of using arrow functions

Scan to Download
according to the author?
Answer:Arrow functions are always anonymous, which can
compromise code readability. The author advises that while
they are useful for their lexical 'this' behavior, developers
should be careful to mitigate readability issues when using
them.

[Link]
Why should all functions have names, as suggested by the
author?
Answer:All functions should have names to provide clarity
about their purpose and functionality. Named functions
improve debuggability because stack traces become more
informative, helping developers quickly identify issues.

[Link]
What is the 'temporal dead zone' (TDZ) and why is it
significant?
Answer:The TDZ refers to the period where variables
declared with 'let' and 'const' are hoisted but not initialized,
making them inaccessible. This mechanism is significant as

Scan to Download
it prevents confusion over variable states before their
declaration, enforcing more intentional coding practices.

[Link]
What should you avoid doing with function parameters
according to the author's advice?
Answer:You should avoid shadowing parameters with local
variables. Doing so can lead to confusion and bugs due to the
conflicting scopes of the same variable name.

[Link]
How does the author advise handling default parameters
in functions?
Answer:The author advises caution when using default
parameters, especially when they reference other parameters,
as it can lead to unexpected behaviors due to the scope and
initialization order.

[Link]
What is one piece of advice the author gives regarding
naming functions during the code writing process?
Answer:If you're unsure of a function's purpose and can't
think of a good name while writing it, use 'TODO' as a

Scan to Download
placeholder. This prompts you to revisit and name it
appropriately later.

[Link]
What is the purpose of named functions in relation to
stack traces and debugging?
Answer:Named functions provide descriptive context in
stack traces, which makes debugging easier compared to
having 'anonymous' functions that don't indicate what went
wrong or where.

[Link]
Why is the author critical of using 'const' with mutable
values?
Answer:The author criticizes using 'const' with mutable
values because it creates a misleading implication that those
values can't change, which can confuse future developers
about the actual mutability of the data.
Chapter 11 | Appendix B: Practice| Q&A
[Link]
What impact does caching have on performance in
programming, according to the content?

Scan to Download
Answer:Caching can significantly improve
computation speed, especially for repeated
operations, potentially by a dramatic amount.
However, it comes with the trade-off of increased
memory usage due to the growing cache.

[Link]
What should one consider when deciding to implement a
cache in their code?
Answer:One must consider the likelihood of seeing repeated
inputs to justify the memory cost of caching; if inputs are
typically unique, caching may become an inappropriate
technique.

[Link]
What is the purpose of the `toggle` function exercise?
Answer:The `toggle` function exercise aims to practice
closures by creating a utility that alternates between multiple
values each time it is called.

[Link]
Why are closures important in JavaScript as highlighted
in the exercise about calculating prime factors?

Scan to Download
Answer:Closures are essential because they allow functions
to retain access to their lexical scope even when called
outside that scope, enabling features like caching, which
improves efficiency.

[Link]
What programming paradigm is employed when
converting the calculator exercise into a module format?
Answer:The module pattern enables encapsulation in
JavaScript, allowing for multiple calculator instances to be
created, enhancing modularity and code organization.

[Link]
What are the key factors to examine when comparing
module design versus closure design for the calculator?
Answer:When comparing designs, consider ease of use,
readability, encapsulation, and flexibility in creating multiple
instances.

[Link]
What is one potential complexity added when using a
Least Recently Used (LRU) cache compared to basic
caching?

Scan to Download
Answer:Implementing an LRU cache adds complexity as it
requires tracking which items are used, managing the cache
size, and evicting the least recently used items appropriately.

[Link]
How do the exercises emphasize that there can be
multiple solutions to a programming problem?
Answer:The exercises encourage readers to explore different
approaches, stating that solutions are not definitive but serve
as examples to illustrate diverse coding strategies.

[Link]
In the context of creating a calculator, what key user
interface feature is referenced regarding operations
entered?
Answer:The calculator should process operations strictly in
the order they are entered, without considering operator
precedence or grouping, reflecting how a physical calculator
operates.

[Link]
What conclusion does the author reach at the end of the
chapter?

Scan to Download
Answer:The author congratulates the reader on their progress
through the book and encourages transitioning to the next
book, focusing on 'Objects & Classes'.

Scan to Download
You Don't Know JS Yet Quiz and Test
Check the Correct Answer on Bookey Website

Chapter 1 | You Don't Know JS Yet: Scope &


Closures| Quiz and Test
[Link] is purely an interpreted language.
[Link] affects the behavior of variables by resolving their
scope during the execution phase.
[Link] JavaScript, the roles of variables can be classified as
either targets for assignment or sources of values, which is
essential for understanding scope.
Chapter 2 | What’s the Scope?| Quiz and Test
[Link] is predominantly an interpreted
language.
[Link] allows variable declarations to be processed
before execution in JavaScript.
[Link] scope determines the visibility and lifetime of
variables based on their position in the nested structure of
code.
Chapter 3 | Illustrating Lexical Scope| Quiz and Test

Scan to Download
[Link] access in JavaScript is determined at
runtime.
[Link] JavaScript, shadowing can occur when an inner scope
has a variable with the same name as an outer scope
variable.
[Link] functions in JavaScript introduce a different
behavior regarding lexical scope compared to traditional
functions.

Scan to Download
Chapter 4 | The Scope Chain| Quiz and Test
[Link] global scope in JavaScript is often
downplayed due to the emphasis on functions and
modules, but it remains critical in programming.
[Link] ES modules, top-level declarations create global
variables accessible from anywhere in the application.
[Link] global scope in [Link] behaves the same as in the
browser, where all variables are automatically global.
Chapter 5 | Around the Global Scope| Quiz and Test
[Link] declarations are hoisted and can be
invoked before they are defined in the code.
[Link] declared with `let` and `const` are hoisted but can
be accessed before their declaration without error.
[Link]-declaring a variable with `var` does result in an error.
Chapter 6 | The (Not So) Secret Lifecycle of
Variables| Quiz and Test
[Link] define their scopes, while blocks also
contribute to scope creation.
[Link] `var` for variable declarations offers the same

Scan to Download
scoping rules as `let` and `const`.
[Link] Invoked Function Expressions (IIFE) can
create scopes without risk of naming collisions.

Scan to Download
Chapter 7 | Limiting Scope Exposure| Quiz and Test
[Link] refers to the ability of a function to access
variables from outside its own scope even when it
is invoked outside that scope.
[Link] do not maintain a live link to the variable itself,
meaning updates to the variable do not reflect in the
closure.
[Link] is advisable to keep references to large variables even
when they are no longer necessary to prevent memory
issues.
Chapter 8 | Using Closures| Quiz and Test
[Link] utilize the concept of lexical scope and
closure to manage data and function visibility
effectively.
[Link] Least Exposure Principle (POLE) encourages
maximum exposure of module elements for easier access in
coding.
[Link] [Link], modules are file-based and properties/functions
inside a module are private by default.

Scan to Download
Chapter 9 | The Module Pattern| Quiz and Test
[Link] in JavaScript are collections of related
data and functions that maintain state over time
and provide functionality to access and modify
that state.
[Link] in JavaScript provide both encapsulation and
state management for functions.
[Link] qualify as a module, an implementation must ensure
both data encapsulation and access control.

Scan to Download
Chapter 10 | Appendix A: Exploring Further| Quiz
and Test
[Link] parameters can create unexpected
scopes, especially with non-simple parameters.
[Link] functions have distinct names that enhance
debugging capabilities compared to named functions.
[Link] allows variable declarations to be accessible
before their definition, making the code easier to read.
Chapter 11 | Appendix B: Practice| Quiz and Test
[Link] chapter encourages attempting exercises
independently before checking solutions.
[Link] 'toggle(..)' function allows for only binary toggling
between two values.
[Link] module pattern in the calculator exercise enables
creating only one calculator instance.

Scan to Download

You might also like