Click on text below to jump to specific point in the video


What are closures? In JavaScript, functions are also closures. That means, the function body has access to variables that are defined outside the function.
Start of demo
We are assigning a variable here called me and a value. We have a function called greetMe. Notice we are not passing in an argument - we are just calling it without any argument - we are directly referring to the me that is assigned outside the function. The reason we can do this is that JavaScript functions are closures. We cannot do this in languages that do not have support for closures. In languages without support for closures, we would have to pass the argument into the function instead. I really like to stress here that greetMe does have access to the outer variable scope. If I reassign me to be a different value it will get the new value.
Why is this useful?
They have quite a bit of use cases - I will give you one.
Example: send request function

We start by assigning a requestID to a variable and use a jQuery ajax function. When successful, we do an alert.

This illustrates a good use of closures.
You start a task and you want to specify something that happens when that task is done with stuff that is available to you when you start the task. Closures make that easy and readable.
Closures permeates the entire language.
There are more use cases. When you use it a lot in your code you will really internalize it. Mozilla has a super useful page on closures on their site.
Video outline created using VideoJots