Image for post
Image for post
Photo by Marek Piwnicki on Unsplash

Most of us who want to learn closure have already used it before. So, we don’t need to learn closure. Instead, we need to recognize closure.

When a function access a variable/another function outside of it, it’s a closure? Don’t worry if it’s confusing. Let's look at an example

Image for post
Image for post

If we call app() function, we get the output “Ronaldo is a good sportsman”. Here, the function app is accessing a player variable which is outside of it. So, it's a closure.

As we know that wrapping some code inside a function doesn’t change its output. Let’s wrap some code inside a wrapper function.

The “app” function can access any variable outside of it even if the variable is outside the wrapper function. So, we can define closure now.

When a function can read/write/create/access a variable which is declared outside of it even when the function is execute outside it’s scope. we call it closure.

Some key facts need to know

  • Variables that are defined inside of a function, as well as the arguments passed to a function, are only accessible inside the function.
  • When a variable is passed as an argument to a function, the value of the variable is copied inside the argument.

Written by

Front-End Developer & Tech Writer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store