what are closures in javascript

what are closures in javascript

1 year ago 37
Nature

Closures in JavaScript are functions that have access to variables from an outer functions scope, even after the outer function has returned. In other words, a closure gives you access to an outer functions scope from an inner function. Closures are created every time a function is created, at function creation time.

Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow you to associate data (the objects properties) with one or more methods. Consequently, you can use a closure anywhere that you might normally use an object with only a single method.

Closures are created automatically whenever a function is created. A block is also treated as a scope since ES6. Since JavaScript is event-driven, closures are useful as they help to maintain the state between events.

In summary, closures are a powerful feature of JavaScript that allow functions to access variables from an outer functions scope, even after the outer function has returned. They are created automatically whenever a function is created and are useful for maintaining state between events in event-driven programming.

Read Entire Article