Meta description: Learn JavaScript closures with simple examples, including lexical scope, private state, and common mistakes with loops.
A closure is a function that can access variables from its outer scope, even after the outer function has finished executing.
function outer() {const message = "Hello, JavaScript!";return () => {console.log(message);};}const myFunc = outer();myFunc(); // Hello, JavaScript!
Even though outer() has finished executing, the returned function can still access message. This is a closure.
Closures retain access to variables in their lexical environment, allowing them to preserve state between function calls.
function createCounter() {let count = 0;return () => {count++;return count;};}const counter = createCounter();console.log(counter()); // 1console.log(counter()); // 2console.log(counter()); // 3
The count variable persists between calls because the returned function maintains access to it.
Closures are commonly used for:
Example of private state:
function createUser() {let name = "Viet";return {getName: () => name,setName: (newName) => {name = newName;},};}const user = createUser();user.setName("Alex");console.log(user.getName()); // Alexconsole.log(user.name); // undefined