JavaScript Closures in Plain Language

Closures are one of the most powerful features of JavaScript.

JavaScript allows for the nesting of functions.

The inner function has full access to all the variables and functions defined in the outer function and everything the outer function has access to.

However, the outer function does not have access to the variables and functions defined inside the inner function.

This provides a sort of encapsulation for the variables of the inner function.

A closure is created when the inner function is somehow made available to any scope outside the outer function.

var pet = function ( name) {   / / The outer function defines a variable called “name”

var getName = function( ) {

return name;                        / / The inner function has access to the”name”variable  of the outer

                                            / /function

}

return getName;.           / / Return the inner

function, thereby exposing it to outer scopes

}

my Pet = pet( ‘Vivie ‘);

my Pet();.                       / /Returns “Vivie”

return getName;.           / / Return the inner

function, thereby exposing it to outer scopes

}

my Pet = pet( ‘Vivie ‘);

my Pet();.                       / /Returns “Vivie”

Closures help in maintaining the state between function calls without using a global variable.

Leave a Reply

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