JavaScript Closures & Lexical Environment Quiz

JavaScript
0 Passed
0% acceptance

Study 40 JavaScript questions on lexical scoping, scope chains, closure creation, accessing outer variables, state preservation, memory considerations, and avoiding accidental closures.

40 Questions
~80 minutes
1

Question 1

What does lexical scoping determine in JavaScript?

A
Which variables are available based on where functions are defined
B
Which variables are available based on where functions are called
C
How many arguments a function takes
D
Whether a function is synchronous or asynchronous
2

Question 2

Why is JavaScript described as having static scope?

A
Because the scope chain is determined before runtime and does not change per call site
B
Because it cannot allocate memory dynamically
C
Because there is no heap
D
Because it requires type annotations
3

Question 3

What does this code log?

javascript
const label = 'outer'
function print() {
  console.log(label)
}
print()
A
outer
B
undefined
C
Throws ReferenceError
D
null
4

Question 4

Which statement best summarizes lexical scoping?

A
Nested functions inherit access to identifiers defined in parent scopes
B
Functions inherit access only from the global scope
C
Scope is determined by the value of this
D
Scope changes based on event loop order
5

Question 5

What is the scope chain?

A
A linked list of lexical environments consulted when resolving identifiers
B
A queue of callbacks waiting to run
C
A DOM event propagation order
D
A structure that tracks promises
6

Question 6

What logs here?

javascript
const outer = 10
function first() {
  const inner = 20
  function second() {
    console.log(outer + inner)
  }
  second()
}
first()
A
30
B
20
C
10
D
Throws ReferenceError
7

Question 7

How does JavaScript search for a variable during execution?

A
It looks in the current environment first, then walks up the scope chain until it finds a match or reaches global scope
B
It scans all scopes in random order
C
It always queries the global object first
D
It searches only block scopes
8

Question 8

What is a lexical environment record?

A
A structure storing bindings for a specific scope
B
A log of events emitted by a function
C
A stack trace entry
D
A promise registry
9

Question 9

How do inner functions differ from outer functions regarding captured variables?

A
Inner functions can access outer scope variables, while outer functions cannot reach inner scope variables directly
B
Outer functions can read inner scope variables by default
C
Inner functions have access only to global variables
D
Inner functions automatically copy outer values, creating new independent copies
10

Question 10

What prints from this snippet?

javascript
function outer() {
  const secret = 42
  function reveal() {
    return secret
  }
  return reveal
}
const fn = outer()
console.log(fn())
A
42
B
undefined
C
Throws ReferenceError
D
null
11

Question 11

Why can outer functions not access variables declared inside inner functions?

A
Because lexical scope only moves inward to outward, not the opposite
B
Because const declarations cannot be read by parent functions
C
Because functions cannot nest in JavaScript
D
Because the outer function is garbage collected immediately
12

Question 12

What does the term "closure" describe?

A
A function bundled with its lexical environment references
B
A function that immediately executes
C
A class-based inheritance pattern
D
A module import system
13

Question 13

When does JavaScript create a closure for a nested function?

A
When the nested function is defined, storing references to its surrounding lexical environments
B
Only when the function is invoked for the first time
C
Only when strict mode is enabled
D
Only when var is used in the outer scope
14

Question 14

What’s logged here?

javascript
function createCounter() {
  let count = 0
  return () => ++count
}
const inc = createCounter()
console.log(inc())
console.log(inc())
A
1 then 2
B
0 then 0
C
1 then 1
D
Throws ReferenceError
15

Question 15

Why do closures capture references rather than copies of variables?

A
To ensure the latest value is accessible whenever the closure runs
B
To reduce bytecode size
C
To support only primitive types
D
To prevent recursion
16

Question 16

Which of the following is a sign that a closure was created?

A
A function returns another function that still accesses variables from the outer scope
B
A function uses this
C
A function throws an error
D
A function is defined using function keyword instead of arrow syntax
17

Question 17

What prints?

javascript
function setup() {
  const prefix = 'ID-'
  return function make(id) {
    return prefix + id
  }
}
const buildId = setup()
console.log(buildId(7))
A
ID-7
B
7
C
undefined
D
Throws TypeError
18

Question 18

How can closures access block-scoped variables?

A
Closures capture variables defined with let or const as long as they are in the lexical chain
B
Closures only capture var declarations
C
Closures cannot access block scopes
D
Closures only access function scopes
19

Question 19

What happens in this scenario?

javascript
function buildFormatter(locale) {
  return function format(value) {
    return new Intl.NumberFormat(locale).format(value)
  }
}
const formatUS = buildFormatter('en-US')
console.log(formatUS(1234.56))
A
1,234.56
B
Throws ReferenceError
C
1234.56
D
Undefined
20

Question 20

Why do closures enable partial application with ease?

A
They store initial arguments or configuration data for future calls
B
They automatically convert functions to promises
C
They change the value of this to globalThis
D
They inline loops at compile time
21

Question 21

Which example demonstrates accessing outer variables?

A
A function returned from another function that uses an argument from the parent function
B
A function calling itself recursively
C
A function imported from another module
D
A function with default parameters
22

Question 22

What is a common reason to use closures for state?

A
To keep data private and accessible only through specific functions
B
To force values onto the global object
C
To avoid using modules entirely
D
To memoize DOM nodes automatically
23

Question 23

What logs?

javascript
function makeToggle() {
  let isOn = false
  return () => {
    isOn = !isOn
    return isOn
  }
}
const toggle = makeToggle()
console.log(toggle())
console.log(toggle())
A
true then false
B
false then false
C
true then true
D
Throws ReferenceError
24

Question 24

How do closures help simulate private members?

A
By confining variables to the function scope and exposing only specific operations via returned functions
B
By using eval to hide variables
C
By storing everything in localStorage
D
By requiring TypeScript types
25

Question 25

What does this snippet return?

javascript
function createBankAccount(initialBalance) {
  let balance = initialBalance
  return {
    deposit(amount) {
      balance += amount
      return balance
    },
    withdraw(amount) {
      balance -= amount
      return balance
    }
  }
}
const account = createBankAccount(100)
console.log(account.withdraw(40))
A
60
B
100
C
Throws ReferenceError
D
-40
26

Question 26

Which pattern frequently relies on closures?

A
Currying functions to transform multi-argument functions into sequences of single-argument functions
B
Declaring global variables to share across files
C
Switch statements with fall-through
D
JSON serialization
27

Question 27

What is logged?

javascript
const add = a => b => a + b
const addFive = add(5)
console.log(addFive(3))
A
8
B
5
C
3
D
NaN
28

Question 28

Why are closures useful in event handlers?

A
They let handlers access contextual data that existed when the handler was registered
B
They force handlers to run synchronously
C
They prevent event propagation
D
They convert events into promises automatically
29

Question 29

What does this code print?

javascript
function once(fn) {
  let called = false
  let result
  return function (...args) {
    if (!called) {
      result = fn.apply(this, args)
      called = true
    }
    return result
  }
}
const logOnce = once((msg) => msg.toUpperCase())
console.log(logOnce('hello'))
console.log(logOnce('again'))
A
HELLO then HELLO
B
HELLO then AGAIN
C
Throws ReferenceError
D
undefined twice
30

Question 30

How do closures enable module-like patterns?

A
By allowing developers to return only the API while keeping implementation details private inside the closure
B
By bundling files automatically
C
By saving files to disk
D
By generating TypeScript declaration files
31

Question 31

How can closures impact memory usage?

A
They keep referenced variables in memory as long as the closure exists
B
They always free variables immediately
C
They force values into sessionStorage
D
They prevent garbage collection entirely
32

Question 32

What logs?

javascript
function heavy() {
  const largeArray = new Array(1000).fill(0)
  return () => largeArray.length
}
const getLength = heavy()
console.log(getLength())
A
1000
B
undefined
C
Throws ReferenceError
D
0
33

Question 33

How can you avoid holding onto unnecessary data inside closures?

A
Limit captured variables to what is truly needed and null out references when done
B
Use var instead of let
C
Wrap closures in eval
D
Avoid any nested functions
34

Question 34

Why should long-lived closures be profiled?

A
They may retain large structures longer than expected, affecting memory footprint
B
They disable tail-call optimization
C
They turn loops into recursion
D
They automatically throttle CPU usage
35

Question 35

What is a sign you might be creating accidental closures during loops?

A
Callbacks inside a loop all reference the final value of the loop variable unexpectedly
B
The loop stops running
C
The code switches to strict mode
D
The loop variable becomes globalThis
36

Question 36

What is one way to avoid accidental loop closures capturing a single binding?

A
Use let in the loop declaration so each iteration gets a new binding
B
Use var exclusively
C
Avoid functions entirely
D
Disable closures in strict mode
37

Question 37

What prints from this loop?

javascript
const funcs = []
for (let i = 0; i < 3; i += 1) {
  funcs.push(() => i)
}
console.log(funcs[0](), funcs[2]())
A
0 2
B
3 3
C
undefined undefined
D
Throws ReferenceError
38

Question 38

Which scenario often indicates an accidental closure?

A
Event handlers created inside a loop all referencing the same mutable variable unintentionally
B
A single function defined at module scope
C
A function declared with default parameters
D
A function that does not return anything
39

Question 39

How can factory functions help avoid closure-related bugs?

A
Each factory call can return a properly scoped function with predefined data, reducing reliance on outer mutable variables
B
Factories eliminate the need for unit tests
C
Factories remove the event loop
D
Factories prevent promises from rejecting
40

Question 40

What is a best practice when using closures heavily?

A
Document which variables are captured and ensure they represent intentional state
B
Avoid using const declarations
C
Always convert closures into classes
D
Disable strict mode to simplify scope

QUIZZES IN JavaScript