Home >Web Front-end >JS Tutorial >What Are JavaScript Closures?

What Are JavaScript Closures?

PHPz
PHPzOriginal
2024-08-30 18:37:50276browse

What Are JavaScript Closures?

Let's talk about a JavaScript feature that is simple to understand but powerful when mastered: Closures.

They are functions that have access to their own scope, the outer function’s scope, and the global scope. They allow a function to remember the environment where it was created, even after that function is executed.

Consider this example:

function createCounter() {
 let count = 0; // This `count` is enclosed in the closure

 return function() { // The returned function forms a closure
 count++;
 console.log(count);
 };
}

const counter = createCounter();
counter(); // Output: 1
counter(); // Output: 2

Here, createCounter creates a closure that "remembers" the count variable even after it’s done executing. Every time you call counter(), it still has access to count!

Closures allow us to create private variables, implement function factories, and write more modular and maintainable code.


To stay updated with more content related to web development and AI, feel free to follow me. Let's learn and grow together!

The above is the detailed content of What Are JavaScript Closures?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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