Understanding Closures In JavaScript Day 5
Closure is one of important concept in JavaScript. It is widely discussed and still confused concept.
Most of the JavaScript developers use Closures consciously or unconsciously.
- Even if they do unconsciously it works fine in most of the cases. But knowing closure will provide better control over the code when using them.
- And another reason for learning closure is that it is the most frequently asked question in the interview for the JavaScript developers.
- Closure means that an inner function always has access to the vars and parameters of its outer function, even after the outer function has returned.
Local variables are declared when the function is completed.
A function can also access variables defined outside the function.
Global variables are declared when you close the browser window (or tab).
A function can also access variables defined inside the function.
Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript.
The two types of scope are local and global :
- Global variables are those declared outside of a block.
- Local variables are those declared inside of a block.
Closures have been hard to explain traditionally because, despite their usefulness, they work silently in the background to make things work, the stuff we take for granted. In this article, I’ll try to cover the basics of what a closure is and why JavaScript benefits from closures.
A closure can be defined as a persistent scope that is held onto by a variable. Languages like JavaScript and Ruby support closures, which allows variables to have references to their parent scope even after their programming block has been executed and, as long as these variable have a reference somewhere, the closure exists.
Comments
Post a Comment