Defining Closure

August 28, 2020 ยท 1 min read

I was once asked to explain what closure is in a technical interview, and I struggled with it. I have an understanding of the concept, but couldn't put it into my own words how to define what closure is.

It's best to describe it in terms of how functions are expected to work in programming. A function is used to carry out some logic or rules only when the function is called somewhere in the program. No matter how many times the function is called, each instance is self contained.

Check out the example below. total1 passes the value 4 to the function double() which doubles it (8), then returns a function that squares the value, thus returning 64. This function call is one instance of its use. Which is why calling double() again with the value 5 returns 100.

function double(num) {
  num += num;
  return function square() {
    return num ** 2;
  };
}

let total1 = double(4);
console.log(total1()); //64

let total2 = double(5);
console.log(total2()) //100

I also wanted to take a concept mentioned in Eloquent JavaScript that emphasizes closure:

When called, the function body sees the environment in which it was created, not the environment in which it is called.

Source

Each time the function is called, a new instance is created that only looks at what logic is contained inside it, not where in the code it is called from.

Found a typo or problem? Edit this page.