Opening the Door on Closures

Please read my previous post “Let’s Talk About Scopes Baby…” before you continue on as a proper understanding of Scopes is necessary to grasp the beauty of the closure.

Time to tackle Closures, an extremely useful tool when it comes to programming in JavaScript. Their usability varies depending on who you are and you’re personal preference when it comes to coding, but they do help when it comes to the readability and styling of your code which are VERY important factors to be considered.

Closures are functions that consist of a function within a function, so an outer function and an inner function. Below is a basic example of a closure function:

Screen Shot 2016-03-12 at 9.00.55 PM (1)

Below is what is printed to the console:

Screen Shot 2016-03-12 at 9.00.55 PM

Notice how


simply logs


to the console. If I call the .toString() method on innerCall this is what is logged :


Screen Shot 2016-03-12 at 9.31.40 PM

Essentially the variable innerCall now contains the function that was returned from the outerFunc function, making it invocable. The cool thing is that the variables from outeFunc are still available to innerCall so when it is invoked it has access to it’s own variable and can access the outer functions variables by reference. Below is an example of how this could come in handy :

Screen Shot 2016-03-12 at 10.18.53 PM

Pretty straight forward right? I hope this has shed some light on closures and their uses, if you have any questions feel free to comment.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s