bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

JavaScript Closures

JavaScript variables can belong to

  • The local scope
  • The global scope

Global variables can be made local (private) with closures .

Closures make it possible for a function to have "private" variables.

A closure is created when a function remembers the variables from its outer scope, even after the outer function has finished executing.

Closures are an advanced topic.

Make sure you understand JavaScript functions and scope first.

JavaScript Functions

JavaScript Scope

Local Variables

A local variable is a "private" variable defined inside a function.

A function can access all variables in the local scope .

Example

function myFunction() {
  let a = 4;
  return a * a;
}

Global Variables

A global variable is a "public" variable defined outside a function.

A function can access all variables in the global scope :

Example

let a = 4;
function myFunction() {
  return a * a;
}

In a web page, global variables belong to the page.

Global variables can be used (or changed) by all scripts in the page.

A local variable can only be used inside the function where it is defined. It is private and hidden from other functions and other scripting code.

Global and local variables with the same name are different variables. Modifying one, does not modify the other.

Undeclared variables (created without a keyword var , let , const ), are always global , even if they are created inside a function.

Example

function myFunction() {
  a = 4;
}

Variable Lifetime

Global variables live until the page is discarded, like when you navigate to another page or close the window.

Local variables have short lives. They are created when the function is invoked, and deleted when the function is finished.

A Counter Dilemma

Suppose you want to use a variable for counting something, and you want this counter to be available to everyone (all functions).

You could use a global variable, and a function to increase the counter:

Example

// Initiate counter
let counter = 0;
// Function to increment counter function add() { counter += 1;
}
// Call add() 3 times add(); add(); add(); // The counter should now be 3

Warning !

There is a problem with the solution above: Any code on the page can change the counter, without calling add() .

The counter should be local to the add() function, to prevent other code from changing it:

Example

// Initiate counter
let counter = 0;
// Function to increment counter function add() {
let counter = 0;
counter += 1;
}
// Call add() 3 times add(); add(); add(); // The counter should now be 3. But it is 0

It did not work because we display the global counter instead of the local counter.

We can remove the global counter and access the local counter by letting the function return it:

Example

// Function to increment counter function add() {
let counter = 0;
counter += 1;
return counter;
}
let x= 0;
// Call add() 3 times x = add(); x = add(); x = add(); // The counter should now be 3. But it is 1.

It did not work because we reset the local counter every time we call the function.

Solution

A JavaScript inner function can solve this.

JavaScript Nested Functions

All functions have access to the global scope.

In fact, in JavaScript, all functions have access to the scope "above" them.

JavaScript supports nested functions. Nested functions have access to the scope "above" them.

plus()

This could have solved the counter dilemma, if we could reach the plus() function from the outside.

We also need to find a way to execute counter = 0 only once.

Solution

We need a closure.

JavaScript Closures

Example

function myCounter() {
  let counter = 0;
  return function() {
    counter++;
    return counter;
  };
}
const add = myCounter();
add();
add();
add();
// the counter is now 3

Example Explained

The variable add is assigned to the return value of a function.

The function only runs once. It sets the counter to zero (0), and returns a function expression.

This way add becomes a function. The "wonderful" part is that it can access the counter in its parent scope.

This is called a closure. It makes it possible for a function to have " private " variables.

The counter is protected by the scope of the myCounter function, and can only be changed using the add function.

Conclusion

A closure is a function that has access to the parent scope, after the parent function has closed.

Closures has historically been used to

  • Create private variables
  • Preserve state between function calls
  • Simulate block-scoping before let and const existed
  • Implement certain design patterns like currying and memoization

Old JavaScript code often contains closures, but modern JavaScript will not use closures as frequently.

ECMAScript 2015 and subsequent JavaScript versions have introduced new language features that provide alternatives to closures.

Modern Alternative: Private Class Fields

Since ECMAScript 2022, JavaScript supports real private class fields using the # syntax.

Private fields are enforced by the language and cannot be accessed outside the class.

All modern browsers support private class fields.

Example

class Counter {
 #count = 0;
 increment() {
 this.#count++;
 return this.#count;
 }
}
const myCounter = new Counter();
myCounter.increment();

Private class fields are usually preferred when working with classes.

  • They provide true privacy.
  • They are simpler than closure-based patterns inside classes.
  • They are part of the official ECMAScript standard.

Closures are still important and useful outside of classes.

Closures are also widely used in older codebases and functional programming patterns.

Previous

JavaScript PlainMonthDay

Next

JavaScript Temporal PlainTime

This chapter

Overview
123

Lessons

539m

Read time

1. JavaScript Objects2. JavaScript Temporal Tutorial3. JavaScript Loops4. JavaScript Advanced Functions5. JavaScript Objects6. JavaScript Temporal Intro7. JavaScript Iterables8. JavaScript Function Definitions9. JavaScript Object Properties10. JavaScript Temporal vs Date11. JavaScript Iterators12. JavaScript Callbacks13. JavaScript Object Methods14. JavaScript Temporal Duration15. JavaScript Generators16. The JavaScript this Keyword17. JavaScript this Keyword18. JavaScript Temporal Instant19. JavaScript Function call()20. JavaScript Display Objects21. JavaScript PlainDateTime22. JavaScript Function apply()23. JavaScript Object Constructors24. JavaScript Temporal PlainDate25. JavaScript Function bind()26. JavaScript PlainYearMonth27. Self-Invoking Functions28. JavaScript PlainMonthDay29. JavaScript Closures30. JavaScript Temporal PlainTime31. JavaScript Objects - Advanced32. JavaScript ZonedDateTime33. JavaScript Object Definitions34. JavaScript Temporal Now35. this in JavaScript Objects36. JS Temporal Arithmetic37. JavaScript Object Iterations38. JS Temporal Differences39. JavaScript Object Accessors40. JS Temporal Compare41. JavaScript Object Management42. JavaScript Temporal Conversion43. JavaScript Object Protection44. Temporal Display Formats45. JavaScript Object Prototypes46. JavaScript Temporal Mistakes47. JavaScript Classes48. Migrate from Date to Temporal49. JavaScript Class Inheritance50. Temporal Standards51. JavaScript Static Methods52. Asynchronous JavaScript53. Asynchronous Programming54. JavaScript Timeouts55. JavaScript Callbacks56. JavaScript Promises57. JavaScript async and await58. JavaScript fetch API59. Debugging Async JavaScript60. JavaScript Modules61. JavaScript Modules Export62. JavaScript Modules Import63. JS Module Namespace64. JavaScript Dynamic Modules65. JavaScript Meta Programming66. JavaScript Reflect67. JavaScript Proxy68. JavaScript Typed Arrays69. Typed Array Methods70. JavaScript ArrayBuffer71. JavaScript DataView72. JavaScript Atomics73. JavaScript HTML DOM Navigation74. JavaScript HTML DOM Elements (Nodes)75. JavaScript HTML DOM Collections76. JavaScript HTML DOM Node Lists77. JavaScript Window - The Browser Object Model78. JavaScript Window Screen79. JavaScript Window Location80. JavaScript Window History81. JavaScript Window Navigator82. JavaScript Popup Boxes83. JavaScript Timing Events84. JavaScript Cookies85. Web APIs - Introduction86. JavaScript Fetch API87. Web Geolocation API88. Web History API89. Pointer Events API90. Web Storage API91. JavaScript Validation API92. Web Workers API93. AJAX Introduction94. AJAX - The XMLHttpRequest Object95. AJAX - XMLHttpRequest96. AJAX - Server Response97. AJAX XML Example98. AJAX PHP Example99. AJAX ASP Example100. AJAX Database Example101. XML Applications102. JavaScript JSON103. JSON Syntax104. JSON vs XML105. JSON Data Types106. JSON.parse()107. JSON.stringify()108. JSON Object Literals109. JSON Array Literals110. JSON PHP111. JSON HTML112. JSONP113. JavaScript / jQuery DOM Selectors114. JavaScript / jQuery HTML Elements115. JavaScript / jQuery CSS Styles116. JavaScript / jQuery HTML DOM117. JavaScript Graphics118. HTML Canvas119. Plotly.js120. Chart.js121. Google Chart122. D3.js123. JavaScript Interview Preparation

On this page

Local VariablesGlobal VariablesVariable LifetimeA Counter DilemmaWarning !SolutionJavaScript Nested FunctionsSolutionJavaScript ClosuresExample ExplainedConclusionModern Alternative: Private Class Fields