Closures are a fundamental concept in JavaScript that can seem tricky but are incredibly powerful. Here's a quick guide to understanding them.
A closure is created when a function "remembers" the variables from its lexical scope, even after that scope has exited.
function outerFunction(outerVariable) { return function innerFunction(innerVariable) { console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`); }; } const myClosure = outerFunction("Hello"); myClosure("World"); // Output: Outer: Hello, Inner: World
Here, innerFunction has access to outerVariable from outerFunction's scope, even after outerFunction has finished executing.
function counter() { let count = 0; return function () { count++; return count; }; } const myCounter = counter(); console.log(myCounter()); // 1 console.log(myCounter()); // 2
function multiplyBy(multiplier) { return function (number) { return number * multiplier; }; } const double = multiplyBy(2); console.log(double(5)); // 10
Closures let functions remember their environment. They’re great for private variables, partial application, and many other advanced patterns in JavaScript.
The above is the detailed content of What Are Closures in JavaScript? (inute Guide). For more information, please follow other related articles on the PHP Chinese website!