rick and morty

A closure is a way to get access to the data inside the scope of a function using a inner function and calling it outside, without expose the variables and functions that you want to keep private.

Remember this tale:

Once upon a time there was a train crossing a bridge…

To create a simple closure you need 3 things: a private variable(passenger), an inner function accessing it(train) and a way to grant access to this function(bridge).

function foo(){ // 1 - A private variable inside foo scope is our passenger.



var passenger = 'Pickle Riiiiiick!'; // 2 - the train takes 'a', that is in the scope of foo, to cross the bridge.



function train(){

console.log(passenger);

}



//3 - The bridge grant access to our passenger to the other side. return train; } //foo is reserved in a variable.

var baz = foo();

//The bridge stops here where the variable call directly the inner function.

baz(); //output: 'Pickle Riiiiiick!'

And it is pretty much it!

A closure is what the return does granting access to an inner function that access something in the scope of foo .

Here another way to make a closure: