Discussion Javascript

Closure in javascript

A closure is the combination of a function and the lexical environment within which that function was declared.

This environment consists of any local variables that were in-scope at the time the closure was created.

Closures are useful because they let you associate some data (the lexical environment) with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow us to associate some data (the object’s 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.

Situations where you might want to do this are particularly common on the web. Much of the code we write in front-end JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *