JS Built-ins
Closuresbeginner

Closures β€” Boolean toggle

πŸ“– Usage Example
function makeToggle() {
  let state = true
  return () => (state = !state)
}
const toggle = makeToggle()
toggle()  // β†’ true
toggle()  // β†’ false

A closure remembers its private state between calls, allowing a toggle to alternate its value each time it is invoked.

Toggle State Between Two Values

Create a simple toggle function that alternates between true and false on each call.

Challenge: Create a makeToggle() function that returns a function. Each call to the returned function alternates between returning true and false, starting with true.

Example:

const toggle = makeToggle()
toggle() // true
toggle() // false
toggle() // true
toggle() // false
πŸ’‘ Hints (2)
  • β€’ Toggle boolean using the NOT operator (!)
  • β€’ Store state in a closure variable