What are closures and callbacks in JavaScript? I’ve yet to find a good explanation of either.
What are closures and callbacks in JavaScript? I’ve yet to find a good explanation
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Closures have already been well handled in Stackoverflow here is just a selection:-
How does a javascript closure work?
What exactly does “closure” refer to in JavaScript?
can you say this is a right example of Javascript Closure.. Where the places we need to consider avoiding the closures??
JavaScript scope and closure
Javascript Closures and ‘this’ context
JavaScript – How do I learn about “closures” usage?
Callbacks are a simpler concept. A callback is basically where a function accepts another function as a parameter. At some point during execution the called function will execute the function passed as a parameter, this is a callback. Quite often the callback actually happens as an asynchronous event, in which case the called function may return without having executed the callback, that may happen later. Here is a common (browser based) example:-
Here the function
fnis passed as a callback to thesetTimeoutfunction. Set timeout returns immediately however 5 seconds later the function passed as a callback is executed.Closures and callbacks
Quite often the reason that closures get created (either incidentally, accidentally or deliberately) is the need to create a callback. For example:-
(Please read some of the linked posts to grasp closures)
A closure is created containing in part the
messageparameter,fnis executed quite some time after the call toAlertThisLaterhas returned, yetfnstill has access to the original content ofmessage.