HOW DO JAVASCRIPT CLOSURES WORK?

How do JavaScript closures work?

Closure is related to Scope. Let’s assume that we have a function named ‘Outer’. Inside this function, let’s create a ‘inner’ function. Looks something like below:

function outer(){
function inner(){
}}

Let’s create a variable in outer function. Now, the inner function will have access to this outer function variable. The inner function is now a closure.

function outer(){
var info = “Hello”;
function inner(){
console.log(info); //Prints Hello – inner() fn has access to info var
}}

So, to put it in as a text book definition, A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain.The inner function shall have access to three different scope vars:

• It’s own variables
• Outer function variables
• Global variables
var greet = “Welcome”;
function outer(){
var info = “Hello”;
function inner(){
var name = “James”;
console.log(info); //Prints Hello – inner() fn has access to info var
console.log(name); //Prints James
console.log(greet); //Prints Welcome
}
}
P.S: The inner function shall have access to the outer function parameters as well
Dispelling the Myths of closure:
Myth 1. Closures are created only after an inner function has been returned
Myth 2. Closures only apply to inner functions

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>