{"id":1167,"date":"2023-06-19T20:53:07","date_gmt":"2023-06-19T15:23:07","guid":{"rendered":"https:\/\/idevelop.pro\/blog\/?p=1167"},"modified":"2023-06-23T21:55:48","modified_gmt":"2023-06-23T16:25:48","slug":"what-are-javascript-closures-cheatsheet-series","status":"publish","type":"post","link":"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/","title":{"rendered":"Learn JavaScript Closures with examples: What is Lexical Scoping? JavaScript PRO Cheatsheet Series"},"content":{"rendered":"\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_83 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#What_are_exactly_JavaScript_Closures\" >What are exactly JavaScript Closures?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Introduction_to_JavaScript_Closures\" >Introduction to JavaScript Closures<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Define_closures_and_their_relationship_to_lexical_scoping\" >Define closures and their relationship to lexical scoping<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Explain_the_concept_of_capturing_variables_from_the_surrounding_scope\" >Explain the concept of capturing variables from the surrounding scope<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Benefits_of_closures_in_JavaScript_development\" >Benefits of closures in JavaScript development<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#How_Closures_Work_in_JavaScript\" >How Closures Work in JavaScript<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Real-life_example\" >Real-life example:<\/a><\/li><\/ul><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Creating_Closures_in_JavaScript\" >Creating Closures in JavaScript<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Returning_Functions_from_Functions\" >Returning Functions from Functions:<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Immediately_Invoked_Function_Expressions_IIFEs\" >Immediately Invoked Function Expressions (IIFEs)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Closure_Factories\" >Closure Factories<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Practical_Examples_of_Closures_Exploring_Real-Life_Use_Cases\" >Practical Examples of Closures: Exploring Real-Life Use Cases<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Event_Handlers\" >Event Handlers<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Private_Variables\" >Private Variables<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Memoization\" >Memoization<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Iterators\" >Iterators<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Function_Factories\" >Function Factories<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Benefits_of_Closures\" >Benefits of Closures<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Real-life_example-2\" >Real-life example<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Common_Mistakes_Developer_Makes\" >Common Mistakes Developer Makes<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-21\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Memory_Management_and_Garbage_Collection_with_Closures\" >Memory Management and Garbage Collection with Closures<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-22\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Best_Practices_for_Working_with_Closures\" >Best Practices for Working with Closures<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-23\" href=\"https:\/\/idevelop.pro\/blog\/what-are-javascript-closures-cheatsheet-series\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"What_are_exactly_JavaScript_Closures\"><\/span>What are exactly JavaScript Closures?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine you have a <strong>treasure chest<\/strong> \ud83c\udf81, and you want to keep it secure from others. You put a <strong>lock<\/strong> \ud83d\udd12 on it, and only you have the <strong>key<\/strong> \ud83d\udd11 to open it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In JavaScript, <strong>closures<\/strong> work in a similar way. They act like self-contained <strong>bubbles<\/strong> that store information and functions, keeping them safe from outside interference.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of a function that creates a <strong>counter<\/strong> \ud83d\udd22. Each time you call this function, it returns a new counter that starts from zero. But here&#8217;s the interesting part: the counter is stored within the <em>javascript closures<\/em>, so it remembers its value even after the function finishes executing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For instance, let&#8217;s consider a function called <em><span style=\"text-decoration: underline;\">createCounter<\/span><\/em>. When you call this function, it creates a closure and returns another function, which serves as the actual counter. Every time you invoke this counter function, it increments the count and returns the updated value.<\/p>\n\n\n\n<pre><code class=\"language-javascript\">function createCounter() {\n  let count = 0;\n\n  return function() {\n    return ++count;\n  };\n}\n\nconst counter1 = createCounter();\nconsole.log(counter1()); \/\/ Output: 1\nconsole.log(counter1()); \/\/ Output: 2\n\nconst counter2 = createCounter();\nconsole.log(counter2()); \/\/ Output: 1\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Introduction_to_JavaScript_Closures\"><\/span>Introduction to JavaScript Closures<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Define_closures_and_their_relationship_to_lexical_scoping\"><\/span>Define closures and their relationship to lexical scoping<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In JavaScript, closures are like self-contained bundles of functionality that retain access to variables from their surrounding scope. It&#8217;s similar to how a backpack holds essential items you need on a hiking trip. Let&#8217;s consider an example:<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nfunction hikingTrip() {\n  const backpack = ['water bottle', 'snacks'];\n\n  function addItem(item) {\n    backpack.push(item);\n    console.log(`Added ${item} to the backpack.`);\n  }\n\n  function showItems() {\n    console.log('Items in the backpack:', backpack.join(', '));\n  }\n\n  return {\n    addItem,\n    showItems\n  };\n}\n\nconst trip = hikingTrip();\ntrip.addItem('compass');\ntrip.showItems();\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here, the &#8216;hikingTrip&#8217; function creates a closure that includes the &#8216;backpack&#8217; array and two inner functions: &#8216;addItem&#8217; and &#8216;showItems&#8217;. The &#8216;addItem&#8217; function adds an item to the backpack, while the &#8216;showItems&#8217; function displays the items in the backpack. Despite the &#8216;hikingTrip&#8217; function finishing execution, the inner functions still have access to the &#8216;backpack&#8217; variable due to closures.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Explain_the_concept_of_capturing_variables_from_the_surrounding_scope\"><\/span>Explain the concept of capturing variables from the surrounding scope<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Closures capture variables from their outer scope, allowing inner functions to access and use those variables. Let&#8217;s see another example:<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nfunction outerFunction() {\n  const outerVariable = 'I am from the outer function';\n\n  function innerFunction() {\n    console.log(outerVariable);\n  }\n\n  return innerFunction;\n}\n\nconst closure = outerFunction();\nclosure();\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this example, the &#8216;outerFunction&#8217; defines an &#8216;outerVariable&#8217;. The &#8216;innerFunction&#8217; is returned and assigned to the &#8216;closure&#8217; variable. When we invoke &#8216;closure()&#8217; it logs the value of &#8216;outerVariable&#8217;. The inner function captures the &#8216;outerVariable&#8217; from its surrounding scope, even though the outer function has already finished executing.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Benefits_of_closures_in_JavaScript_development\"><\/span>Benefits of closures in JavaScript development<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Encapsulation and data privacy<\/li>\n\n\n\n<li>Persistent data and state preservation<\/li>\n\n\n\n<li>Modularity and code organization<\/li>\n\n\n\n<li>Handling callbacks and asynchronous operations<\/li>\n\n\n\n<li>Supporting functional programming paradigms<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"How_Closures_Work_in_JavaScript\"><\/span>How Closures Work in JavaScript<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Understanding the internal mechanisms:\n<ul class=\"wp-block-list\">\n<li>Closures are created when a function is defined inside another function.<\/li>\n\n\n\n<li>The inner function has access to variables in its own scope, as well as variables in the outer function&#8217;s scope.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>The closure scope chain:\n<ul class=\"wp-block-list\">\n<li>Closures have access to variables in their own scope, the scope of the outer function, and any other outer functions in the scope chain.<\/li>\n\n\n\n<li>This is possible due to the [[Environment]] internal property, which maintains references to the variables.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Retaining access to the lexical environment:\n<ul class=\"wp-block-list\">\n<li>Even after the outer function has finished executing, closures retain access to the variables in their lexical environment.<\/li>\n\n\n\n<li>This allows them to access and manipulate those variables, even when they are called from a different context.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Real-life_example\"><\/span>Real-life example:<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s say you have a website that allows users to create and manage their own to-do lists. Each user has their own separate list of tasks. To achieve this, you can use closures.<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nfunction createUser() {\n  const tasks = [];\n\n  return {\n    addTask: function(task) {\n      tasks.push(task);\n      console.log(`Task \"${task}\" added.`);\n    },\n    getTasks: function() {\n      console.log(\"Tasks:\", tasks);\n    },\n  };\n}\n\nconst user1 = createUser();\nconst user2 = createUser();\n\nuser1.addTask(\"Buy groceries\"); \/\/ Output: Task \"Buy groceries\" added.\nuser1.addTask(\"Pay bills\"); \/\/ Output: Task \"Pay bills\" added.\nuser2.addTask(\"Walk the dog\"); \/\/ Output: Task \"Walk the dog\" added.\n\nuser1.getTasks(); \/\/ Output: Tasks: [\"Buy groceries\", \"Pay bills\"]\nuser2.getTasks(); \/\/ Output: Tasks: [\"Walk the dog\"]\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this example, the &#8216;createUser&#8217; function creates a new user with an empty array of tasks. The &#8216;addTask&#8217; and &#8216;getTasks&#8217; functions are returned as an object, forming closures over the &#8216;tasks&#8217; array.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each user can add tasks to their own list by calling the &#8216;addTask&#8217; function, and they can retrieve their tasks by calling the &#8216;getTasks&#8217; function. Since each closure retains its own separate tasks array, the &#8216;tasks&#8217; are isolated and unique to each user.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This demonstrates how closures in JavaScript can encapsulate data and provide a way to maintain separate states for different instances or contexts.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Creating_Closures_in_JavaScript\"><\/span>Creating Closures in JavaScript<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Creating closures in JavaScript involves different methods that allow you to encapsulate and capture variables within functions. Let&#8217;s explore a few common techniques:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Returning_Functions_from_Functions\"><\/span>Returning Functions from Functions:<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<pre><code class=\"language-javascript\">\nfunction outerFunction() {\n  let message = 'Hello';\n\n  function innerFunction() {\n    console.log(message);\n  }\n\n  return innerFunction;\n}\n\nconst myClosure = outerFunction();\nmyClosure(); \/\/ Output: Hello\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this approach, you can define a function that returns another function, effectively creating a closure. The inner function has access to the variables defined in the outer function&#8217;s scope.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Immediately_Invoked_Function_Expressions_IIFEs\"><\/span>Immediately Invoked Function Expressions (IIFEs)<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">An IIFE is a self-invoking function that is executed immediately. It allows you to create a private scope and preserve data within it.<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nconst myClosure = (function() {\n  let counter = 0;\n\n  return function() {\n    counter++;\n    console.log(counter);\n  };\n})();\n\nmyClosure(); \/\/ Output: 1\nmyClosure(); \/\/ Output: 2\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Closure_Factories\"><\/span>Closure Factories<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A closure factory is a function that generates and returns closures with specific configurations. It allows you to create multiple closures with different captured variables.<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nfunction closureFactory(value) {\n  return function() {\n    console.log(`The value is: ${value}`);\n  };\n}\n\nconst closure1 = closureFactory('Apple');\nconst closure2 = closureFactory('Banana');\n\nclosure1(); \/\/ Output: The value is: Apple\nclosure2(); \/\/ Output: The value is: Banana\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">By utilizing these techniques, you can create closures in JavaScript. These examples demonstrate how closures can be used in real-life scenarios to solve programming challenges.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Practical_Examples_of_Closures_Exploring_Real-Life_Use_Cases\"><\/span>Practical Examples of Closures: Exploring Real-Life Use Cases<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In practical terms, closures can be extremely useful in various scenarios.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Event_Handlers\"><\/span>Event Handlers<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Closures can be used to create event handlers that maintain access to their surrounding scope.<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nfunction createEventHandler() {\n  let count = 0;\n  \n  return function() {\n    count++;\n    console.log(`Button clicked ${count} times.`);\n  };\n}\n\nconst button = document.querySelector('#myButton');\nbutton.addEventListener('click', createEventHandler());\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Private_Variables\"><\/span>Private Variables<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Closures enable the creation of private variables and functions.<br><\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nfunction createCounter() {\n  let count = 0;\n  \n  function increment() {\n    count++;\n    console.log(`Current count: ${count}`);\n  }\n  \n  return increment;\n}\n\nconst counter = createCounter();\ncounter(); \/\/ Output: Current count: 1\ncounter(); \/\/ Output: Current count: 2\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Memoization\"><\/span>Memoization<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Closures can be used to implement memoization, which caches the results of expensive function calls.<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nfunction memoize(fn) {\n  const cache = {};\n  \n  return function(arg) {\n    if (arg in cache) {\n      return cache[arg];\n    } else {\n      const result = fn(arg);\n      cache[arg] = result;\n      return result;\n    }\n  };\n}\n\nfunction calculateExpensiveValue(num) {\n  \/\/ Expensive computation\n  return num * 2;\n}\n\nconst memoizedCalculation = memoize(calculateExpensiveValue);\nconsole.log(memoizedCalculation(5)); \/\/ Output: 10 (Computed)\nconsole.log(memoizedCalculation(5)); \/\/ Output: 10 (Cached)\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Iterators\"><\/span>Iterators<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Closures can be used to create custom iterators that remember their current state.<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nfunction createIterator(array) {\n  let index = 0;\n  \n  return function() {\n    if (index < array.length) {\n      return array[index++];\n    } else {\n      return undefined;\n    }\n  };\n}\n\nconst myIterator = createIterator([1, 2, 3]);\nconsole.log(myIterator()); \/\/ Output: 1\nconsole.log(myIterator()); \/\/ Output: 2\nconsole.log(myIterator()); \/\/ Output: 3\nconsole.log(myIterator()); \/\/ Output: undefined\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Function_Factories\"><\/span>Function Factories<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Closures can be used to create function factories that generate specialized functions.<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nfunction createMultiplier(factor) {\n  return function(number) {\n    return number * factor;\n  };\n}\n\nconst double = createMultiplier(2);\nconsole.log(double(5)); \/\/ Output: 10\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Benefits_of_Closures\"><\/span>Benefits of Closures<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Encapsulation<\/strong>: Closures enable data privacy by encapsulating variables within a function, preventing access from outside scopes.<\/li>\n\n\n\n<li><strong>Persistent Data<\/strong>: Closures preserve the state of variables, allowing them to retain their values even after the outer function has completed execution.<\/li>\n\n\n\n<li><strong>Code Modularity<\/strong>: Closures facilitate modular code by allowing functions to access variables from the outer scope, promoting code organization and reusability.<\/li>\n\n\n\n<li><strong>Callbacks and Asynchronous Operations<\/strong>: Closures are commonly used in handling callbacks, enabling the execution of functions after certain events or asynchronous operations.<\/li>\n\n\n\n<li><strong>Functional Programming<\/strong>: Closures support functional programming concepts like higher-order functions and currying, making it easier to write concise and expressive code.<\/li>\n\n\n\n<li><strong>Memory Efficiency<\/strong>: Closures ensure efficient memory management by automatically handling the garbage collection of unused variables.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Real-life_example-2\"><\/span>Real-life example<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine a shopping cart function in an e-commerce website. By using closures, you can encapsulate the cart items and provide methods to add, remove, and calculate the total cost, ensuring data privacy and maintaining the state of the cart throughout the user's shopping session.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These benefits make closures a powerful feature in JavaScript, enhancing code flexibility, maintainability, and performance.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Common_Mistakes_Developer_Makes\"><\/span>Common Mistakes Developer Makes<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Memory Leaks<\/strong>: Forgetting to properly release closures can lead to memory leaks, where unused variables and functions still hold references in memory. It's important to be mindful of closures' lifecycles and ensure they are released when no longer needed.<\/li>\n\n\n\n<li><strong>Accidental Variable Sharing<\/strong>: Due to lexical scoping, closures can capture variables from the outer scope. However, if not used carefully, this can result in unexpected variable sharing between different closures. To prevent this, always declare variables with the appropriate scope and avoid reusing variable names across different closures.<\/li>\n\n\n\n<li><strong>Outdated Values<\/strong>: Closures can hold references to variables, which means they can retain outdated values if not managed properly. This commonly occurs when closures are used within loops, causing them to capture the last iterated value instead of the expected value at the time of creation. To avoid this, utilize techniques like immediately invoked function expressions (IIFE) or block-scoping to create a new scope for each iteration.<\/li>\n\n\n\n<li><strong>Best Practices<\/strong>: To mitigate common mistakes and pitfalls with closures, follow these best practices:\n<ul class=\"wp-block-list\">\n<li>Always declare variables with <em>let<\/em> or <em>const<\/em> to ensure block-level scoping.<\/li>\n\n\n\n<li>Use function parameters instead of directly accessing variables from the outer scope.<\/li>\n\n\n\n<li>Avoid creating unnecessary closures by moving functions outside of loops or repetitive code blocks.<\/li>\n\n\n\n<li>Be mindful of memory usage and release closures when they are no longer needed.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">By understanding these common mistakes and following best practices, developers can effectively utilize closures while minimizing potential pitfalls and ensuring efficient and error-free code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Memory_Management_and_Garbage_Collection_with_Closures\"><\/span>Memory Management and Garbage Collection with Closures<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Let's consider an example to understand the implications of closures on memory management. Suppose we have a function called <em><span style=\"text-decoration: underline;\">calculateMultiplier<\/span> <\/em>that takes a parameter <span style=\"text-decoration: underline;\"><em>x<\/em><\/span> and returns a new function that multiplies any given number by <span style=\"text-decoration: underline;\"><em>x<\/em><\/span>. Here's how it looks:<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nfunction calculateMultiplier(x) {\n  return function(y) {\n    return x * y;\n  };\n}\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Now, let's say we create multiple instances of this closure:<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nconst multiplyByTwo = calculateMultiplier(2);\nconst multiplyByThree = calculateMultiplier(3);\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Each instance of the closure retains a reference to its outer scope, which includes the <em><span style=\"text-decoration: underline;\">x<\/span><\/em> parameter. This means that even after we're done using <em><span style=\"text-decoration: underline;\">multiplyByTwo<\/span><\/em> or <em><span style=\"text-decoration: underline;\">multiplyByThree<\/span><\/em>, the closures still hold references to <em><span style=\"text-decoration: underline;\">x<\/span><\/em>, potentially leading to memory leaks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To optimize memory usage, we can release these closures and their associated resources when they are no longer needed. For example:<\/p>\n\n\n\n<pre><code class=\"language-javascript\">\nconst multiplyByTwo = calculateMultiplier(2);\n\/\/ Use multiplyByTwo for necessary operations\n\n\/\/ Release the closure and its associated resources\nmultiplyByTwo = null;\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">By explicitly setting the closure to <em><span style=\"text-decoration: underline;\">null<\/span><\/em>, we allow the garbage collector to free up the memory associated with that closure, ensuring efficient memory management and preventing unnecessary memory consumption.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Remembering to release closures and being mindful of their impact on memory can help us optimize memory usage and prevent memory leaks in JavaScript applications.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Best_Practices_for_Working_with_Closures\"><\/span>Best Practices for Working with Closures<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Limit Variable Scope<\/strong>: To avoid unexpected behaviors and memory leaks, it's important to keep the scope of your variables as narrow as possible within the closure. Declare variables only where they are needed and avoid unnecessary global variables.<\/li>\n\n\n\n<li><strong>Avoid Overusing Closures<\/strong>: While closures are a powerful tool, it's important to use them judiciously. Overusing closures can lead to complex and hard-to-maintain code. Consider whether a closure is truly necessary for the task at hand before implementing it.<\/li>\n\n\n\n<li><strong>Avoid Circular References<\/strong>: Be cautious when creating closures that reference objects or variables in a way that can lead to circular references. Circular references can prevent the garbage collector from cleaning up memory properly, resulting in memory leaks.<\/li>\n\n\n\n<li><strong>Use Function Parameters<\/strong>: Instead of relying on variables from the outer scope directly, pass necessary values as function parameters to your closures. This promotes code clarity, making it easier to understand where the values are coming from.<\/li>\n\n\n\n<li><strong>Use Proper Naming Conventions<\/strong>: Choose meaningful and descriptive names for your closure variables and functions. This improves code readability and makes it easier for others (and yourself) to understand the purpose and functionality of the closure.<\/li>\n\n\n\n<li><strong>Document Your Closures<\/strong>: Commenting and documenting your closures can be immensely helpful, especially when working on collaborative projects or when revisiting code later. Describe the purpose, inputs, and outputs of your closure to provide clarity to other developers.<\/li>\n\n\n\n<li><strong>Test and Debug<\/strong>: Always test your closures thoroughly to ensure they behave as expected. Use debugging techniques and tools to identify and resolve any issues or unexpected behaviors that may arise.<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In conclusion, I encourage you to delve deeper into closures, apply them in your projects, and continue learning. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Please feel free to leave your thoughts, share this guide with others, and don't hesitate to reach out if you have any questions or need further assistance. Happy coding! \ud83d\udcbb\u2728<\/p>\n\n\n\n<pre class=\"wp-block-verse\">Ready to continue exploring JavaScript? Go back to the JavaScript Cheatsheet Series and level up your coding skills! <a href=\"https:\/\/idevelop.pro\/blog\/javascript-cheatsheet-series-for-pro\/\" data-type=\"post\" data-id=\"1151\">JavaScript Cheatsheet Series<\/a><\/pre>\n","protected":false},"excerpt":{"rendered":"<p> A personal journey into the world of JavaScript Closures, sharing expert insights, practical examples, and best practices. #JavaScriptClosures<\/p>\n","protected":false},"author":1,"featured_media":1232,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[45],"tags":[],"class_list":["post-1167","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript"],"_links":{"self":[{"href":"https:\/\/idevelop.pro\/blog\/wp-json\/wp\/v2\/posts\/1167","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/idevelop.pro\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/idevelop.pro\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/idevelop.pro\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/idevelop.pro\/blog\/wp-json\/wp\/v2\/comments?post=1167"}],"version-history":[{"count":42,"href":"https:\/\/idevelop.pro\/blog\/wp-json\/wp\/v2\/posts\/1167\/revisions"}],"predecessor-version":[{"id":1250,"href":"https:\/\/idevelop.pro\/blog\/wp-json\/wp\/v2\/posts\/1167\/revisions\/1250"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/idevelop.pro\/blog\/wp-json\/wp\/v2\/media\/1232"}],"wp:attachment":[{"href":"https:\/\/idevelop.pro\/blog\/wp-json\/wp\/v2\/media?parent=1167"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/idevelop.pro\/blog\/wp-json\/wp\/v2\/categories?post=1167"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/idevelop.pro\/blog\/wp-json\/wp\/v2\/tags?post=1167"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}