What is a closure and what are common use cases?
Suggested answer
A closure is a function that retains access to its outer (lexical) scope's variables even after the outer function has returned. This happens because functions in JavaScript form a closure over the variables in scope at the time of their creation. IIFE (Immediately Invoked Function Expression): (function() { /* private scope */ })(); — creates a private scope in pre-ES6 code. Counter example: function makeCounter() { let count = 0; return () => ++count; } const counter = makeCounter(); — each call to counter() increments the private count variable. Module pattern: Using closures to create private state with public methods. Common pitfall: closures in loops — all callback functions share the same variable reference. Fix with let (block-scoped per iteration) or IIFE to capture the value. LWC class properties are not closures, but event handlers using arrow functions close over the class instance.
Practice content for interview preparation; not an official vendor answer. Verify details against current product documentation.
Community comments (0)
No comments yet.
Sign in or create a free account to add a comment. Comments are moderated before they appear.