What is closure in javascript and why we used clousers in javascript.

Formal definitions don't always help to penetrate "closure", though they do make sense once you understand.

If you learned about closures from PHP5, then you almost need to unlearn all that stuff first. PHP's implementation of closures is as bad and confusing as it gets (you actually need to use a keyword to force a closure!) while javascript's implementation is seriously elegant; it's so simple and natural that many programmers (me included) created closures by accident before we even knew it was a named concept. One day I looked at some code I was developing and said to myself, "that shouldn't work, surely that outer variable is out of scope! What is keeping it alive?" The answer (of course) was that a closure was formed where an outer function's scope (think of it as a little anonymous namespace) was kept alive, even after that outer function had completed and returned; it was kept alive simply by an inner function's use of one of the outer function's variables - no more than that.

THIS is a good place to start though you may need to read it though 2, 3, 4 times.

Other definitions and examples exist on the web but beware; some authors use "closure" as a synonym for "lambda", which is incorrect and very confusing. You will (quite correctly) find "lambda" used in discussions of "closure" but they are NOT the same thing.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.