JS Built-ins
Closuresadvanced

Closures β€” Closure preserves reference (advanced)

πŸ“– Usage Example
const obj = { count: 0 }
const inc = () => ++obj.count
inc()       // β†’ 1
obj.count = 10
inc()       // β†’ 11

Closures capture object references rather than copies, so any mutation to the object is immediately reflected when the closure is later invoked.

Mutable Object References in Closures

A closure captures a reference to an object, so mutations to that object are visible through the closure.

Challenge: Create an object, then create a closure that references it. Modify the object after creating the closure and verify that the closure sees the updated values.

Example:

const obj = { count: 0 }
const incrementCount = () => ++obj.count
incrementCount()    // 1
obj.count = 10
incrementCount()    // 11
πŸ’‘ Hints (3)
  • β€’ Closures capture references, not copies
  • β€’ Objects are mutable, so changes after closure creation are visible
  • β€’ This is different from primitive values which are immutable