Dan D Kim

Let's share stories

Answering this question right can affect your salary tremendously - Javascript closure

2020-02-03 Dan D. Kimjavascript

What is a closure?

It’s quite the buzzword in Javascript programming interviews. I would think that it’s over-used today, but it’s still a popular question. If you are having a Javascript interview, it’s a question you shouldn’t be surprised by.

It’s a pretty common Javascript question. Managers love to ask this question, because it lets them scope out basic Javascript knowledge from just one question.

A previous manager of mine, who hasn’t touched a line of code for 5+ years, would even consider this a must-ask question.

Some could say that answering this question properly can significantly affect the offered salary.

So, what is a closure?

It’s basically a nested function that has access to three scopes:

  • its own scope
  • parent scope
  • global scope


const globalVar = 'global'

function parent () {
  const functionVar = 'function'

  return function local() { // this is a closure function
    const localVar = 'local'
    console.log(`${globalVar} ${functionVar} ${localVar}`)

parent()() // Log: global function local

Note how the closure function local is nested within the parent function. It has access to its parent scope and the global scope, which can be seen by how it can access globalVar and functionVar.

Here’s a common question - can you tell what will be printed out in the code below?

let globalVar = 'global'

function parent () {
  const functionVar = 'function'

  return function local() {
    const localVar = 'local'
    console.log(`${globalVar} ${functionVar} ${localVar}`)

const localFunction = parent()

globalVar = 'dan'

localFunction() // Log: ???

The answer is:

dan function local

That’s simply because a closure close over variables, not values. This basically means that they keep the reference to variables alive, and return the variable when the function is invoked.

If the global variable value changes, the child reference value will change as well.

When do you use a closure?

First, you are probably already using closures.

For example, here is a pretty common one:

[0].map(x => x)

The callback function inside map is a closure because it’s nested within a function that has access to its parent scope.

Having said that, closures are used for object data privacy. It’s a great way to to set up good data privacy practices, because outer scopes cannot access the variables that are inside the child scopes.

Hope you learned something! Happy learning :)