DEV Community

mzakzook
mzakzook

Posted on

JavaScript Closures

As I enter the interviewing stage of my journey I have tried to identify the types of questions that come up when weeding out potential candidates. Frequently, interviewers like to test a candidate's fundamental understanding of a language with simple, yet often misunderstood, coding concepts. One question that seems to come up frequently in JS, is to define a closure and how it can be useful.

A closure is essentially a nested function that allows for a private variable to be stored within the confines of the outer function. This protects the scope of the variable while allowing the inner function to change its value and refer to it when needed.

The closure can be achieved by using an IIFE, an immediately invoked function expression, or by creating a reference variable to access the outer function's return (the inner function).

let testClosure = (function() {
  let a = 1
  return function() {
    a += 1
    return a
  }
})()

The above function, 'testClosure', contains a private variable, 'a', that is set once - when testClosure is defined and self invoked. Each subsequent call to 'testClosure' increments the variable 'a' because it is calling the inner return function. The scope of 'a' allows for modification without falling into global scope, and this is why it is known as a private variable.

My takeaway with closures is that they can be helpful when organizing your code's scope. When you want to track a value outside a function but do not want it residing in global scope, a closure is a great tool to utilize.

Top comments (0)