Forem

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay