Closure Road Sign with dramatic clouds and sky.

Closures

When a function runs, it goes through its code, then completes. Everything goes out of scope. There are times when we might want some information to “hang around”. Let’s start by looking at an example…

Within our IIFE, we have a variable (animalName). We also have a nested function that returns the animalName variable. The problem is that if you run this, it will return that app is undefined because the function is complete and there is no closure to have any of the function’s information live on. You might think that the return statement does that here, but it is within the nested function. So it returns to the outer function. We need to create a closure…

Now, we will get the name “Bongo” returned because the outer return statement creates the closure. It returns a reference to the function.

Happy Coding!

Clay Hess

Share this post

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest
Share on print
Share on email
Skip to content