Closures

Patient Tools

Read, save, and share this guide

Use these quick tools to make this medical article easier to read, print, save, or share with a family member.

Article Summary

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time. A closure is a function that retains access to variables of the context it was...

Key Takeaways

  • This article explains Using Closures (Examples) in simple medical language.
  • This article explains Lex-time in simple medical language.
Educational health guideWritten for patient understanding and clinical awareness.
Reviewed content workflowUse writer and reviewer profiles for stronger trust.
Emergency safety firstUrgent warning signs are highlighted below.

Seek urgent medical care if you notice

These warning signs are general safety guidance. Local emergency numbers and clinical judgment should always come first.

  • Severe symptoms, breathing difficulty, fainting, confusion, or rapidly worsening illness.
  • New weakness, severe pain, high fever, or symptoms after a serious injury.
  • Any symptom that feels urgent, unusual, or unsafe for the patient.
1

Emergency now

Use emergency care for severe, sudden, rapidly worsening, or life-threatening symptoms.

2

See a doctor

Book a professional medical evaluation if symptoms persist, worsen, recur often, affect daily activities, or occur in a high-risk patient.

3

Learn safely

Use this article to understand possible causes, tests, treatment options, prevention, and questions to ask your clinician.

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

A closure is a function that retains access to variables of the context it was created in even after said function call has returned.

function init() {
  var name = "Mozilla" // name is a local variable created by init
  function displayName() {
    // displayName() is the inner function, a closure
    alert(name) // use variable declared in the parent function
  }
  displayName()
}
init()

init() creates a local variable called name and a function called displayName(). The displayName() function is an inner function that is defined inside init() and is available only within the body of the init() function. Note that the displayName() function has no local variables of its own. However, since inner functions have access to the variables of outer functions, displayName() can access the variable name declared in the parent function, init().

This is an example of lexical scoping, which describes how a parser resolves variable names when functions are nested. The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.

var awFunc = function(first) {
  var someFunc = function(second) {
    return first + second
  }
  return someFunc // note that I did not invoke this function i.e. I did not use someFunc(), but I did returned the function itself
}

var someMoreFunc = awFunc("awe") // At this point awFunc has finished running

console.log(someMoreFunc()) // This will return 'aweundefined'

console.log(someMoreFunc("some")) // returns awesome

Using Closures (Examples)

Among other things, closures are commonly used to give objects data privacy. Data privacy is an essential property that helps us program to an interface, not an implementation. This is an important concept that helps us build more robust software because implementation details are more likely to change in breaking ways than interface contracts.

To use a closure, simply define a function inside another function and expose it. To expose a function, return it or pass it to another function.

In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can’t get at the data from an outside scope except through the object’s privileged methods. In JavaScript, any exposed method defined within the closure scope is privileged. For example:

const getSecret = secret => {
  return {
    getPrivileged: () => secret,
  }
}

In the example above, the getPrivileged() method is defined inside the scope of getSecret(), which gives it access to any variables from getSecret(), and makes it a privileged method. In this case, the parameter, secret.

Another example of closure

const outerFunc = () => {
  let name = "Rohan"

  const closureFunc = () => {
    console.log(name)
  }
  return closureFunc()
}

var name = "Paul"

outerFunc() // => Will Print 'Rohan'

So whats going on above

First, when a function runs, a new function Lexical Environment is created automatically. That’s a general rule for all functions. That Lexical Environment is used to store local variables and parameters of the call.

During the function call we have two Lexical Environments: the inner one (for the function call) and the outer one (global):

The inner Lexical Environment corresponds to the current execution of that function.

When code wants to access a variable – it is first searched for in the inner Lexical Environment, then in the outer one, then the more outer one and so on until the end of the chain.

If a variable is not found anywhere, that’s an error in strict mode. Without use strict, an assignment to an undefined variable creates a new global variable, for backwards compatibility.

Some overall key points

Closure

  • A closure is a function that remembers its outer variables and can access them.
  • Combination of a function and the lexical environment within which that function was declared
  • The closure is the function object itself.
  • Accessing variables outside of the immediate lexical scope creates a closure.
  • Happens when we have a nested functions.
  • JavaScript engines also may optimize, discard variables that are unused to save memory.
  • Lexical Environment object lives in the heap as long as there is a function which may use it. And when there are none, it is cleared.
  • All functions in JavaScript are closures.
  • The internal property [[Environment]] of a function, refers to the outer lexical environment

Lets look at this function

function outer() {
  var b = 10
  function inner() {
    var a = 20
    console.log(a + b)
  }
  return inner
}

/*
Here we have two functions:

an outer function outer which has a variable b, and returns the inner function
an inner function inner which has its variable called a, and accesses an outer variable b, within its function body
The scope of variable b is limited to the outer function, and the scope of variable a is limited to the inner function.

Let us now invoke the outer() function, and store the result of the outer() function in a variable X
 */

var X = outer()

Since the variables X is functions, we can execute them. In JavaScript, a function can be executed by adding () after the function name, such as X().

When we execute X(), we are essentially executing the inner function.

If I run < console.log(X()) > the output will be below

30 undefined

So the closure function inner() is getting the value of b = 10 from its enclosing outer() function ever after outer() function has returned.

Let’s see step-by-step what happens when the outer() function is first invoked:

    1. Variable b is created, its scope is limited to the outer() function, and its value is set to 10.
    1. The next line is a function declaration, so nothing to execute.
    1. On the last line, return inner looks for a variable called inner, finds that this variable inner is actually a function, and so returns the entire body of the function inner.
    1. Note that the return statement does not execute the inner function — a function is executed only when followed by () — , but rather the return statement returns the entire body of the function.
    1. The contents returned by the return statement are stored in X.

Thus, X will store the following:

function inner() { var a=20; console.log(a+b); }

This can be easily verified by adding the following to the JavaScript code:

console.log(typeof X) //X is of type function
    1. Function outer() finishes execution, and all variables within the scope of outer() now no longer exist.
    1. This last part is important to understand. Once a function completes its execution, any variables that were defined inside the function scope cease to exist.

The lifespan of a variable defined inside of a function is the lifespan of the function execution.

What this means is that in console.log(a+b), the variable b exists only during the execution of the the outer() function. Once the outer function has finished execution, the variable b no longer exists.

This is the most important point to realize. The variables inside the functions only come into existence when the function is running, and cease to exist once the functions completes execution.

Now see the main point of this exercise – that how a closure function retains its enclosing function’s variable values, even after the enclosing function has returned.
  • A. When we execute X(), we are essentially executing the inner function.

  • B. If I run < console.log(X()) > the output will be below

30
undefined
  • C. So the closure function inner() is getting the value of b = 10 from its enclosing outer() function ever after outer() function has returned.

Let us examine step-by-step what happens when X() is executed the first time:

    1. Variable a is created, and its value is set to 20.
    1. JavaScript now tries to execute a + b. Here is where things get interesting. JavaScript knows that a exists since it just created it. However, variable b no longer exists. Since b is part of the outer function, b would only exist while the outer() function is in execution. Since the outer() function finished execution long before we invoked X(), any variables within the scope of the outer function cease to exist, and hence variable b no longer exists.

Closures

  • A. The inner function can access the variables of the enclosing function due to closures in JavaScript. In other words, the inner function preserves the scope chain of the enclosing function at the time the enclosing function was executed, and thus can access the enclosing function’s variables.

  • B. In our example, the inner function had preserved the value of b=10 when the outer() function was executed, and continued to preserve (closure) it.

  • C. It now refers to its scope chain and notices that it does have the value of variable b within its scope chain, since it had enclosed the value of b within a closure at the point when the outer function had executed.

  • D. Thus, JavaScript knows a=20 and b=10, and can calculate a+b.

So the inner function has three scope chains:

access to its own scope — variable a access to the outer function’s variables — variable b, which it enclosed access to any global variables that may be defined.

When we pass a callback function as an argument to another function, we are only passing the function definition. We are not executing the function in the parameter. In other words, we aren’t passing the function with the trailing pair of executing parenthesis () like we do when we are executing a function.

And since the containing function has the callback function in its parameter as a function definition, it can execute the callback anytime.

Note that the callback function is not executed immediately. It is “called back” (hence the name) at some specified point inside the containing function’s body.

Callback Functions Are Closures

When we pass a callback function as an argument to another function, the callback is executed at some point inside the containing function’s body just as if the callback were defined in the containing function. This means the callback is a closure. As we know, closures have access to the containing function’s scope, so the callback function can access the containing functions’ variables, and even the variables from the global scope.

Basic Principles when Implementing Callback Functions

1> Use Named OR Anonymous Functions as Callbacks – Here’s an example of named callback function

In most use case of Node/Express ecosystem, we use anonymous functions that were defined in the parameter of the containing function. That is one of the common patterns for using callback functions. Another popular pattern is to declare a named function and pass the name of that function to the parameter. Consider this:

// global variable
var allUserData = [];

// generic logStuff function that prints to console - this will be used as a callback function
function logStuff(userData) {
  if (typeof userData === "string") {
    console.log(userData);
  } else if (typeof userData === "object") {
    for (var item in userData) {
      console.log(item + ": " + userData[item]);
    }
  }
}

// A function that takes two parameters, the last one a callback function
function getInput(options, callback) {
  allUserData.push(options);
  callback(options);
}

// When we call the getInput function, we pass logStuff as a parameter.
// So logStuff will be the function that will called back (or executed) inside the getInput function
getInput({ name: "Rich", speciality: "JavaScript" }, logStuff);
//  name: Rich
// speciality: JavaScript

Make Sure Callback is a Function Before Executing It

It is always wise to check that the callback function passed in the parameter is indeed a function before calling it. Also, it is good practice to make the callback function optional.

Let’s refactor the getInput function from the previous example to ensure these checks are in place.

function getInput(options, callback) {
  allUserData.push(options);

  // Make sure the callback is a function
  if (typeof callback === "function") {
    // Call it, since we have confirmed it is callable
    callback(options);
  }
}

Without the check in place, if the getInput function is called either without the callback function as a parameter or in place of a function a non-function is passed, our code will result in a runtime error.

Note the following ways we frequently use callback functions in JavaScript, especially in modern web application development, in libraries, and in frameworks:

For asynchronous execution (such as reading files, and making HTTP requests) In Event Listeners/Handlers In setTimeout and setInterval methods For Generalization: code conciseness.

Lex-time

The first traditional phase of a standard language compiler is called lexing (aka, tokenizing). The lexing process examines a string of source code characters and assigns semantic meaning to the tokens as a result of some stateful parsing.

It is this concept which provides the foundation to understand what lexical scope is and where the name comes from.

To define it somewhat circularly, lexical scope is scope that is defined at lexing time. In other words, lexical scope is based on where variables and blocks of scope are authored, by me, at write time, and thus is (mostly) set in stone by the time the lexer processes my code.

It is considered best practice to treat lexical scope as, in fact, lexical-only, and thus entirely author-time in nature.

Let’s consider this block of code:

foo = a => {
  let b = a * 2

  bar = c => {
    console.log(a, b, c)
  }

  bar(b * 3)
}

foo(2) // => 2 4 12

There are three nested scopes inherent in this code example. It may be helpful to think about these scopes as bubbles inside of each other.

Bubble 1 encompasses the global scope, and has just one identifier in it: foo.

Bubble 2 encompasses the scope of foo, which includes the three identifiers: a, bar and b.

Bubble 3 encompasses the scope of bar, and it includes just one identifier: c.

Scope bubbles are defined by where the blocks of scope are written, which one is nested inside the other, etc. For our understanding just assume, that each function creates a new bubble of scope.

The bubble for bar is entirely contained within the bubble for foo, because (and only because) that’s where we chose to define the function bar.

Notice that these nested bubbles are strictly nested. We’re not talking about Venn diagrams where the bubbles can cross boundaries. In other words, no bubble for some function can simultaneously exist (partially) inside two other outer scope bubbles, just as no function can partially be inside each of two parent functions.

Look-ups

The structure and relative placement of these scope bubbles fully explains to the Engine all the places it needs to look to find an identifier.

In the above code snippet, the Engine executes the console.log(..) statement and goes looking for the three referenced variables ab, and c. It first starts with the innermost scope bubble, the scope of the bar(..) function. It won’t find a there, so it goes up one level, out to the next nearest scope bubble, the scope of foo(..). It finds a there, and so it uses that a. Same thing for b. But c, it does find inside of bar(..).

Had there been a c both inside of bar(..) and inside of foo(..), the console.log(..) statement would have found and used the one in bar(..), never getting to the one in foo(..).

Scope look-up stops once it finds the first match. The same identifier name can be specified at multiple layers of nested scope, which is called “shadowing” (the inner identifier “shadows” the outer identifier). Regardless of shadowing, scope look-up always starts at the innermost scope being executed at the time, and works its way outward/upward until the first match, and stops.

Note: Global variables are also automatically properties of the global object (window in browsers, global in node env), so it is possible to reference a global variable not directly by its lexical name, but instead indirectly as a property reference of the global object.

window.a

This technique gives access to a global variable which would otherwise be inaccessible due to it being shadowed. However, non-global shadowed variables cannot be accessed.

No matter where a function is invoked from, or even how it is invoked, its lexical scope is only defined by where the function was declared.

The lexical scope look-up process only applies to first-class identifiers, such as the ab, and c. If you had a reference to foo.bar.baz in a piece of code, the lexical scope look-up would apply to finding the foo identifier, but once it locates that variable, object property-access rules take over to resolve the bar and baz properties, respectively.

Patient safety assistant

Check your symptom safely

Hi, I am RX Symptom Navigator. I can help you understand what to read next and what warning signs need care.
Warning: Do not use this in emergencies, pregnancy, severe illness, or as a substitute for a doctor. For children or teens, use with a parent/guardian and clinician.
A rural-friendly guide: warning signs, when to see a doctor, related articles, tests to discuss, and OTC safety education.
1 Symptom 2 Severity 3 Safe guidance
First safety question

Is there chest pain, breathing trouble, fainting, confusion, severe bleeding, stroke-like weakness, severe injury, or pregnancy danger sign?

Choose quickly

Browse by body area
Start here: Write or select a symptom. The guide will show warning signs, doctor guidance, diagnostic tests to discuss, OTC safety education, and related RX articles.

Important: This tool is educational only. It cannot diagnose, treat, or replace a doctor. OTC information is not a prescription. In an emergency, contact local emergency services or go to the nearest hospital.

Doctor visit helper

Prepare before seeing a doctor

A simple rural-patient checklist to help you explain symptoms clearly, ask better questions, and avoid unsafe self-treatment.

Safety note: This is not a prescription or diagnosis. For severe symptoms, pregnancy danger signs, children with serious illness, chest pain, breathing difficulty, stroke-like weakness, or major injury, seek urgent care.

Which doctor may help?

Start with a registered doctor or the nearest qualified health center.

What to tell the doctor

  • Write when the problem started and how it changed.
  • Bring old prescriptions, investigation reports, and current medicines.
  • Write allergies, pregnancy status, diabetes, kidney/liver disease, and major past illnesses.
  • Bring one family member if the patient is weak, elderly, confused, or a child.

Questions to ask

  • What is the most likely cause of my symptoms?
  • Which danger signs mean I should go to hospital quickly?
  • Which tests are necessary now, and which can wait?
  • How should I take medicines safely and what side effects should I watch for?
  • When should I come for follow-up?

Tests to discuss

  • Vital signs: temperature, pulse, blood pressure, oxygen saturation
  • Basic physical examination by a clinician
  • CBC, urine test, blood sugar, or imaging only when clinically needed

Avoid these mistakes

  • Do not use antibiotics, steroid tablets/injections, or strong painkillers without proper medical advice.
  • Do not hide pregnancy, kidney disease, ulcer, allergy, or blood thinner use.
  • Do not delay emergency care when danger signs are present.

Medicine safety and first-aid guide

This section is for patient education only. It does not replace a doctor, pharmacist, or emergency care.

Safe first steps

  • Avoid heavy lifting, sudden bending, and prolonged bed rest.
  • Use comfortable posture and gentle movement as tolerated.
  • Discuss physiotherapy, X-ray, or MRI only when clinically needed.

OTC medicine safety

  • For mild back pain, pain-relief medicine may be discussed with a doctor or pharmacist.
  • Avoid repeated painkiller use if you have kidney disease, stomach ulcer, uncontrolled blood pressure, or are taking blood thinners.

Avoid these mistakes

  • Do not start antibiotics without a proper medical decision.
  • Do not use steroid tablets or injections casually for quick relief.
  • Do not delay emergency care because of home remedies.

Get urgent help if

  • Back pain with leg weakness, numbness around private area, loss of urine/stool control, fever, cancer history, or major injury needs urgent care.
Medicine names, dose, and timing must be decided by a qualified clinician or pharmacist after checking age, pregnancy, allergy, other diseases, and current medicines.

For rural patients and family caregivers

Patient health record and symptom diary

Write your symptoms, medicines already taken, test results, and questions before visiting a doctor. This note stays on your device unless you print or copy it.

Doctor to discuss: Doctor / qualified healthcare provider
Tests to discuss with doctor
  • Basic vital signs: temperature, pulse, blood pressure, oxygen level if needed
  • Relevant blood, urine, imaging, or specialist tests only after clinical assessment
Questions to ask
  • What is the most likely cause of my symptoms?
  • Which warning signs mean I should go to emergency care?
  • Which tests are really needed now?
  • Which medicines are safe for my age, pregnancy status, allergy, kidney/liver/stomach condition, and current medicines?

Emergency warning signs such as chest pain, severe breathing difficulty, sudden weakness, confusion, severe dehydration, major injury, or loss of bladder/bowel control need urgent medical care. Do not wait for online information.

Safe pathway to proper treatment

Back pain care roadmap

Use this simple roadmap to understand the next safe steps. It is educational and does not replace examination by a doctor.

Go to emergency care if you notice:
  • New leg weakness, numbness around private area, or loss of bladder/bowel control
  • Back pain after major injury, fever, unexplained weight loss, cancer history, or severe night pain
Doctor / service to discuss: Orthopedic/spine specialist, physical medicine doctor, physiotherapist under guidance, or qualified clinician.
  1. Step 1

    Check danger signs first

    If danger signs are present, seek emergency care and do not wait for online information.

  2. Step 2

    Record the symptom story

    Write when symptoms started, severity, medicines already taken, allergies, pregnancy status, and test results.

  3. Step 3

    Visit a qualified clinician

    A doctor, nurse, or qualified healthcare provider can examine you and decide which tests or treatment are needed.

  4. Step 4

    Do only useful tests

    Discuss neurological examination first. X-ray or MRI may be needed only when red flags, injury, nerve weakness, or persistent severe symptoms are present.

  5. Step 5

    Follow up and return early if worse

    If symptoms worsen, new warning signs appear, or treatment is not helping, return for review quickly.

Rural patient practical tips
  • Take a written symptom diary and all previous prescriptions/test reports.
  • Do not hide medicines already taken, even herbal or over-the-counter medicines.
  • Ask which warning signs mean urgent referral to hospital.
  • Avoid forceful massage or bone-setting when there is weakness, injury, fever, or nerve symptoms.

This roadmap is for education. A real diagnosis and treatment plan requires history, examination, and clinical judgment.

RX Patient Help

Ask a health question safely

Write your symptom story. A health professional or site editor can review it before any answer is prepared. This box is not for emergency care.

Emergency first: Severe chest pain, breathing trouble, unconsciousness, stroke signs, severe injury, heavy bleeding, or rapidly worsening symptoms need urgent local medical care now.

Frequently Asked Questions

Is this article a replacement for a doctor?

No. It is educational content only. Patients should consult a qualified clinician for diagnosis and treatment.

When should I seek urgent care?

Seek urgent care for severe symptoms, rapidly worsening condition, breathing difficulty, severe pain, neurological changes, or any emergency warning sign.

References

Add references, clinical guidelines, textbooks, journal articles, or trusted medical sources here. You can edit this area from the RX Article Professional Blocks panel.