JavaScript Closures for Dummies

Morris Johns has detailed “Closures” alongwith expamples “Closures Are Not Magic”. —This page explains closures so that a programmer can understand them - using working JavaScript code. It is not for gurus nor functional programmers. Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any […]

Morris Johns has detailed “Closures” alongwith expamples “Closures Are Not Magic”. —This page explains closures so that a programmer can understand them - using working JavaScript code. It is not for gurus nor functional programmers.

Closures are not hard to understand once the core concept is grokked. However, they are impossible to understand by reading any academic papers or academically oriented information about them!

This article is intended for programmers with some programming experience in a main-stream language, and who can read the following JavaScript function:
function sayHello(name) { var text = 'Hello ' + name; var sayAlert = function() { alert(text); } sayAlert(); }

An Example of a Closure

Two one sentence summaries:

  • a closure is the local variables for a function - kept alive after the function has returned, or
  • a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)

The following code returns a reference to a function:function sayHello2(name) { var text = 'Hello ' + name; // local variable var sayAlert = function() { alert(text); } return sayAlert; }

Continue to read full post…

ajaxian

Closures, for Dummies

About The Author

Deepak Gupta is a IT & Web Consultant. He is the founder and CEO of diTii.com & DIT Technologies, where he's engaged in providing Technology Consultancy, Design and Development of Desktop, Web and Mobile applications using various tools and softwares. Sign-up for the Email for daily updates. Google+ Profile.