Tuesday , 18 June 2019
Home / Programming / JavaScript / Closures – Advanced JavaScript Tutorial

Closures – Advanced JavaScript Tutorial

Closures allow you to take your JavaScript skills to the next level. Closures are used in almost every JavaScript code you’ve ever seen. You’ve probably ended up using it without knowing it. So, what are closures? A closure is a function inside a function. So, what’s so special about this? Well, you can actually access the variables outside of the inner function.

Let’s take a look at how this is done. Open up your script and clear it. Add this bit of code.

Here we have a function named outerFunction(). It has 1 parameter which can take in any value. It doesn’t really matter. Inside this function, we define another function named innerFunction(). This function also has 1 parameter which can be any value. This function returns the result of val1 and val2.

Lastly, our outerFunction() returns the innerFunction(). So, when we call outerFunction(), do you have an idea of how everything will be executed? Let’s see if you’re right.

We next create a variable named foo. This is assigned the result returned from outerFunction(). Notice that I pass in a string. The result ends up being that we’re returned innerFunction().

Even though our function is finished executing, we still have access to the variables inside this function. It actually isn’t destroyed like most function calls are. Since foo is equal to innerFunction(), then we can use it like a regular function. This can be seen at the last line of our code.

Notice that we’re accessing val1 even though val1 is a parameter of the outerFunction(). You actually get access to the variables and parameters of the outer function.

Why isn’t the innerFunction() execute it even though we return it?

The innerFunction() is just simply returned it doesn’t execute even though you return it. This makes our variable usable as a function.

That’s it! Closures are used in popular libraries such as JQuery. When you use a simple function, any variables created inside that function are set to null and are eligible for garbage collection. When you use closures, all variables are still there and you can use them. To use closures, you just return a function that’s located inside the outer function.


More examples of closures will be shown in future tutorials so you can get used to them. More information about closures can be found here.


About Jasko Koyn

Check Also


Audio – Advanced JavaScript Tutorial

The video and audio objects both have the same events, properties and methods. So, you …

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.