Home > Web Front-end > JS Tutorial > What Are Closures in JavaScript? (inute Guide)

What Are Closures in JavaScript? (inute Guide)

DDD
Release: 2024-11-22 03:42:24
Original
345 people have browsed it

What Are Closures in JavaScript? (inute Guide)

What Are Closures in JavaScript?

Closures are a fundamental concept in JavaScript that can seem tricky but are incredibly powerful. Here's a quick guide to understanding them.

What is a Closure?

A closure is created when a function "remembers" the variables from its lexical scope, even after that scope has exited.

Example:

function outerFunction(outerVariable) {  
  return function innerFunction(innerVariable) {  
    console.log(`Outer: ${outerVariable}, Inner: ${innerVariable}`);  
  };  
}  

const myClosure = outerFunction("Hello");  
myClosure("World");  
// Output: Outer: Hello, Inner: World
Copy after login

Here, innerFunction has access to outerVariable from outerFunction's scope, even after outerFunction has finished executing.

Why Are Closures Useful?

Data Privacy: Create private variables.

function counter() {  
  let count = 0;  
  return function () {  
    count++;  
    return count;  
  };  
}  
const myCounter = counter();  
console.log(myCounter()); // 1
console.log(myCounter()); // 2  
Copy after login

Partial Application: Pre-fill function arguments.

function multiplyBy(multiplier) {  
  return function (number) {  
    return number * multiplier;  
  };  
}  
const double = multiplyBy(2);  
console.log(double(5)); // 10  
Copy after login

Conclusion

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template