DEV Community

mzakzook
mzakzook

Posted on

3 2

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.

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❀ or a friendly comment on this post if you found it helpful!

Okay