Closures in Javascript

Jackie Ha
2 min readFeb 4, 2019

--

Can you explain what a closure is? Can you give me an example of a closure?

The short answer is: a closure is a feature in Javascript where an inner function has access to an outer function’s variables.

A closure means that an inner function has access to its own scope, then an outer function’s variables, and then global variables. The inner function remembers the environment in which it was defined. A closure is created when a function is created, and to use it, you would need to define a function inside another function and return that function, or pass it to another function.

In the example below, we have an outer enclosing function called outerFunction, which has a variable of privateVariable that is equal to the string “This is basically private”. The outerFunction returns the inner function of innerFunction, which in turn returns privateVariable. We invoke the outerFunction twice because we are returning the whole function, and we get the string we were looking for. Our outerFunction does three things:

  1. outerFunction defines a local variable of privateVariable
  2. outerFunction defines a function called innerFunction, which has access to the outerFunction’s variable of privateVariable
  3. and it returns innerFunction

The innerFunction is able to return privateVariable because privateVariable was defined in the scope in which the closure was created, within the outer function.

This example of a closure would return the string “this is basically private”

In the example below, our outer function is introduction, which takes in two arguments, first name and last name. We have a variable called hello, and an inner function called makeName, which returns hello + the first name passed in as an argument + the last name passed in as an argument. The function introduction returns makeName, and when we console log introduction(“Sherlock”, “Holmes”), we get a string that equals “Hello Sherlock Holmes”. In this case, the inner function of makeName had access to the outer function’s (introduction) variable and was able to use it to put the string together.

console logging the outer function with the arguments would return “Hello Sherlock Holmes”

--

--