JavaScript Interview Prep: What is a “closure”?

The standard answer I hear in interviews is something along the lines of

A closure is the environment which has the value of variables that the function is referencing

I may have used that answer or something very similar in the past. I actually consider that a satisfactory answer during the interview, but it is not accurate. The answer is satisfactory because it indicates the candidate knows of the implication of static/lexical scoping (even if they are not familiar with the term) and with a followup a conversation or two you can determine that they can leverage closures in their applications.

However access to variables defined in code blocks in scope at the time a code block (e.g. a function) is the feature delivered by a closure not the definition of the closure itself. So here is a definition of closure I plan on using the next time I am asked:

A closure is a data structure, often called the activation record, defined within the call frame data structure (the structure of records on the call stack). The activation record points to the (another) call frame of the code block (e.g. the function) that defined the code block in question.

The activation record allows a programmer to reference variables defined outside of the a functions local scope, but defined in some containing code block. The interpreter/compiler is able to accomplish referencing these non-local variables by walking the linked list of activation records looking for the first definition it encounters.

This is transparent to the coder who only needs to know whether their language supports closures and can knows their function can access the variable of enclosing code blocks.

To see how an interpreter / complier implements closure take a look at my corresponding article: https://medium.com/@akaphenom/javascript-closures-and-the-call-stack-722ef2c3b5a8

A 25 year software industry veteran with a passion for functional programming, architecture, mentoring / team development, xp/agile and doing the right thing.

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