Closure and this in JavaScript – Scope Memory and Dynamic Execution Context

Closure and this are two foundational and often misunderstood concepts in JavaScript. This article defines closure as a function’s ability to remember variables from its outer scope, and explains how this refers to the dynamic execution context of a function call. Through practical examples, it clarifies the difference between static scope and dynamic context.

closurethisexecution-contextscope

~3 min read · Updated Oct 20, 2025

What Is Closure?


Closure occurs when a function remembers variables from its outer scope and continues to access them even when executed in a different scope. Only functions have closures — not objects. To observe closure, a function must be called outside its original definition scope.


Example:


function greeting(msg) {
  return function who(name) {
    console.log(`${msg}, ${name}!`);
  };
}
var hello = greeting("Hello");
var howdy = greeting("Howdy");

hello("Kyle");  // Hello, Kyle!
hello("Sarah"); // Hello, Sarah!
howdy("Grant"); // Howdy, Grant!

The inner function who remembers msg from its outer scope, even after greeting finishes executing.


Closure with Mutable Data:


function counter(step = 1) {
  var count = 0;
  return function increaseCount() {
    count = count + step;
    return count;
  };
}
var incBy1 = counter(1);
var incBy3 = counter(3);

incBy1(); // 1
incBy1(); // 2
incBy3(); // 3
incBy3(); // 6

The inner function increaseCount closes over both count and step, preserving and updating their values over time.


Closure in Asynchronous Code:


function getSomeData(url) {
  ajax(url, function onResponse(resp) {
    console.log(`Response (from ${url}): ${resp}`);
  });
}

The callback onResponse remembers url even after getSomeData has returned.


Closure in Loops:


for (let [idx, btn] of buttons.entries()) {
  btn.addEventListener("click", function onClick() {
    console.log(`Clicked on button (${idx})!`);
  });
}

Each onClick function remembers its respective idx variable thanks to block scoping with let.


What Is `this`?


The this keyword refers to the execution context of a function call. Unlike scope, which is static and tied to where a function is defined, this is dynamic and depends on how the function is called.


Example:


function classroom(teacher) {
  return function study() {
    console.log(`${teacher} says to study ${this.topic}`);
  };
}
var assignment = classroom("Kyle");

assignment(); // Kyle says to study undefined

Called without context, this.topic resolves to undefined.


Calling with Execution Context:


var homework = {
  topic: "JS",
  assignment: assignment
};
homework.assignment(); // Kyle says to study JS

Here, this refers to the homework object.


Calling with `call`:


var otherHomework = {
  topic: "Math"
};
assignment.call(otherHomework); // Kyle says to study Math

call sets this to otherHomework, allowing dynamic reuse of the function.


Conclusion


Closure lets functions preserve and access outer variables, while `this` provides dynamic context based on how a function is called. Understanding both concepts is essential for writing professional, maintainable JavaScript code.


Written & researched by Dr. Shahin Siami

Related Articles

Coercive Conditional Comparison and Prototypal Classes in JavaScript – Understanding Implicit Logic and Legacy Inheritance Patterns

This article explores two advanced topics from Appendix A of You Don’t Know JS Yet: how JavaScript performs coercive comparisons in conditional expressions, and how prototypal class patterns were used before ES6 introduced the class keyword. Through practical examples, it clarifies how implicit boolean logic works and how prototype chains enable behavior delegation.

Continue

Value vs Reference and the Many Forms of Function Definitions

Value vs Reference and the Many Forms of Function Definitions

Continue

Prototypes in JavaScript – Delegation, Prototype Chains, and Dynamic this Behavior

Prototypes in JavaScript provide a mechanism for property delegation between objects. This article explains how prototype chains work, how to create linked objects using Object.create, and how property access and assignment behave in relation to delegation. It also explores how the dynamic nature of this enables prototype-based method reuse across multiple objects.

Continue

Iteration in JavaScript – The Iterator Pattern, Built-in Iterables, and Standard Data Consumption

Iteration is a foundational pattern for processing data in JavaScript. This article explores the iterator protocol, how to consume iterators using for..of loops and the spread operator, the distinction between iterators and iterables, and how built-in structures like arrays, strings, maps, and sets support standardized iteration. It also shows how to customize iteration for your own data structures.

Continue

Modules in JavaScript – From Classic Patterns to ES Modules and Structural Differences

Modules in JavaScript, like classes, are designed to group data and behavior into logical units. This article explores the classic module pattern using factory functions, compares it to class-based design, and introduces ES Modules (ESM) introduced in ES6. It explains how modules are defined, exported, imported, and instantiated, and highlights the differences in structure and usage.

Continue

Organizing Code in JavaScript – Classes, Modules, and Object-Oriented Inheritance

JavaScript offers two major patterns for organizing code: classes and modules. This article focuses on class-based design, including how to define and instantiate classes, encapsulate data and behavior, and use inheritance and polymorphism to extend functionality. Understanding these patterns helps developers write clean, maintainable, and scalable programs.

Continue