Categories
Javascript Tech

Closures in JavaScript

A closure in JavaScript is a function that has access to variables in its outer scope, even after the outer function has returned. A closure is created when a function is defined inside another function and the inner function references variables in the outer function’s scope.

Closures allow you to preserve the state of a function’s variables even after the function has returned, and they can be used to create powerful and flexible functions that can be reused in different parts of your code.

Here’s a simple example of a closure in JavaScript:

function outerFunction(x) {
return function innerFunction(y) {
return x + y;
}
}

const add5 = outerFunction(5);
console.log(add5(3)); // 8

In this example, the outerFunction returns the innerFunction, which has access to the x variable in its outer scope. When we call outerFunction(5), it returns the innerFunction with x set to 5, and we assign it to the add5 variable. When we later call add5(3), it returns the result of x + y, which is 8.

Closures are an important concept in JavaScript, as they can be used to create functions that have private variables, to implement object-oriented concepts like classes and prototypes, and to manage state and data in complex applications.

Source: AI Interaction Channel

Happy Learning!