DEV Community

Cover image for Closures in Javascript PART-1
Shivaansh Agarwal
Shivaansh Agarwal

Posted on

1 1

Closures in Javascript PART-1

DISCLAIMER: I've written this blog to share with others what I've understood after going through several blogs, articles, videos, etc. So the following written blog might contain some ideas & language influenced by those.


Overview

Closures are one of the most asked interview topics & are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.

Definition

  • A closure is a function bundled together with it's lexical environment.
  • In simple words a closure gives you access from an outer function's scope from an inner function.
  • In Javascript, a closure is created every time a function is created, at function creation time.

Lexical Scoping

The following is an example of lexical scoping, where getName() has 2 local variables firstName & lastName.

It also has a nested method which is accessing these variables of it's other function.

carbon
JSFiddle Link
Lexical Scoping describes how a parser resolves variable names when functions are nested.

Closures

Now what happens if we return this nested method and call it from outside?

carbon (1)
JS Fiddle Link
It works exactly the same as in previous example.
The catch here is when we return the function, it is returned along with its lexical environment. The lexical environment of the inner function getFullName consists of any local variables that were in-scope at the time when closure was created.

References:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
  2. https://javascript.info/closure
  3. https://www.youtube.com/watch?v=qikxEIxsXco
  4. https://www.youtube.com/watch?v=71AtaJpJHw0

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay