{"id":5286,"date":"2021-09-10T00:01:00","date_gmt":"2021-09-09T18:31:00","guid":{"rendered":"https:\/\/blog.guvi.in\/?p=5286"},"modified":"2025-10-29T16:02:27","modified_gmt":"2025-10-29T10:32:27","slug":"the-beginners-guide-to-javascript-closures","status":"publish","type":"post","link":"https:\/\/www.guvi.in\/blog\/the-beginners-guide-to-javascript-closures\/","title":{"rendered":"The Beginner&#8217;s Guide To Closures In JavaScript"},"content":{"rendered":"\n<p>If you&#8217;re a beginner and wondering what are closures in JavaScript, you&#8217;ve come to the right place. In this blog, we&#8217;ll be talking about closures in JavaScript. Let&#8217;s understand more about its history, advantages, and some examples to understand its functioning. They are crucial in functional programming, and hence they\u2019re something that is frequently asked about during the JavaScript coding interview.<\/p>\n\n\n\n<p><strong>Without much ado, let&#8217;s read about it:<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What are Closures?<\/h2>\n\n\n\n<p><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Closures\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Closures<\/strong> <\/a>are one of the very basic building blocks in JavaScript. Undoubtedly, every JavaScript developer must have come across closures! And would have used Closures knowingly or unknowingly. The callbacks, higher-order, and event handler functions can access variables from the outer scope, thanks to closures. To understand <em>closures<\/em>, one first needs to understand Lexical Environment (or <strong>Lexical Scoping<\/strong>).&nbsp;<\/p>\n\n\n\n<p><em>Before diving into the next section, ensure you&#8217;re solid on full-stack development essentials like front-end frameworks, back-end technologies, and database management. If you are looking for a detailed Full Stack Development career program, you can join <a href=\"https:\/\/www.guvi.in\/zen-class\/full-stack-development-course\/?utm_source=blog&amp;utm_medium=organic&amp;utm_campaign=Closures-in-JavaScript\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>HCL GUVI\u2019s Full Stack Development Career Program<\/strong><\/a> with placement assistance. You will be able to master the <a href=\"https:\/\/www.guvi.in\/blog\/guide-for-mern-stack\/\" target=\"_blank\" rel=\"noreferrer noopener\">MERN stack<\/a><\/em> <em>(MongoDB, Express.js, React, Node.js) and build real-life projects.<\/em><\/p>\n\n\n\n<p><em>Additionally, if you would like to explore JavaScript through a self-paced course, try<a href=\"https:\/\/www.guvi.in\/courses\/web-development\/advanced-javascript\/?utm_source=blog&amp;utm_medium=organic&amp;utm_campaign=Closures-in-JavaScript\" target=\"_blank\" rel=\"noreferrer noopener\"> <strong>HCL GUVI\u2019s JavaScript self-paced certification course.<\/strong><\/a><\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What is Lexical Scope?<\/h2>\n\n\n\n<p>A <strong>Lexical scope<\/strong> in JavaScript means that variables defined outside of a function can be accessed inside of another function that was defined after the declaration of the variable. However, variables defined inside a function will not be accessible outside that function. Every function in JavaScript maintains a link to its outer lexical environment that maps all the names (E.g. variables, parameters) within a scope, along with their values.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh6.googleusercontent.com\/dt_4n-be2GOOrc27co99cxMSVZybzyEXimJVEoNnM5fOpLm5uNGuDg_wiz43iq4zdDvDZn6OlicsoEpY0_NMRh7T2zYQc1JGm9uD7yGXJ7hbqP9wCWedjMTjvUJsASFv-j7sflI=s0\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<p>In the above-written code, JavaScript searches for values a and b. It begins to look locally and goes outside until it finds what it is looking for. However, if we remove the variable declaration of \u2018a\u2019 in line no. 1, JavaScript will not go inside the multiply function and will throw an Undefined Error.<\/p>\n\n\n\n<p>This is known as a Lexical scope. We can determine the scope of a component by the location of this component within the code.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Closures in JavaScript <\/h2>\n\n\n\n<p><strong>Now, coming to the main question, What are closures and how do<\/strong> they<strong> work?<\/strong><\/p>\n\n\n\n<p>According to the definition given on<strong> <em>MDN (Mozilla Developer Network) <\/em><\/strong><em>Web Docs<\/em>,<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\">\n<p><em>\u201c<strong>Closures<\/strong> are the combination of a function bundled together (enclosed) with references to its surrounding state (the <\/em><strong><em>lexical environment<\/em><\/strong><em>).\u201d<\/em><\/p>\n<\/blockquote>\n\n\n\n<p>However, this is not the simplest definition and hence, hard to understand by beginners so let\u2019s break this down in simpler words:<\/p>\n\n\n\n<p><strong>A closures function gives access to an outer function\u2019s scope from an inner function.<\/strong> It is the combination of a function and the surrounding state (lexical environment) within which that specific function was declared. Now, the lexical environment consists of all the local variables that were inside scope at the time the closures were made. We can create a closures function by defining a function inside another one. And then exposing it by returning or passing it to another function.<\/p>\n\n\n\n<p>The function declared inside will have access to all the variables in the function from the outer scope, even after the outer function is done executing.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh4.googleusercontent.com\/2T_eSbCBRks8a0qts-IgfFDBg-qPwr-E2-xxvrBJZy8E1557gfvSRwH-9CdiJOAE1pIJpKsr6NS7nVS4gHeMJNSGv6k2I3hyULBgeo1TcpfVWn4wqkrvGsKEYXp1jyBmSxBkAcI=s0\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Closures in JavaScript Simplified For You<\/h3>\n\n\n\n<p>In the example of the closures above, we have defined a function <em>multiply(a)<\/em> that returns an <em>anonymous function<\/em>. The function it returns takes a single argument <em>b<\/em> and returns the multiplication of <em>a<\/em> and <em>b<\/em>. Let&#8217;s consider that multiply is a function factory that makes functions that can multiply a certain value to the argument passed. In the above example, the function factory creates two new functions &#8211; one that multiplies 10 to its argument, and one that multiplies 20.<\/p>\n\n\n\n<p>When the code is given in line no. 7 and line no. 8 get executed multiple functions are called and stored in their respective variables. As you might be expecting after the execution, arguments passed would no longer be accessible but this is not the case. Variables multiplyBy10 and multiplyBy20 hold a reference to the anonymous function which was returned when function multiply was called with arguments 10 and 20, respectively. The instance of the returned anonymous function maintains a reference to its lexical environment, within which the passed arguments exist.<\/p>\n\n\n\n<p><strong><em>multiplyBy10<\/em> and <em>multiplyBy20<\/em> are both closures.<\/strong> They have the same function definition but store different lexical environments and variable values. In <em>multiplyBy10 <\/em>the lexical environment of a is 10, while in the lexical environment for <em>multiplyBy20<\/em>, a is 20.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Running the Code<\/strong><\/h3>\n\n\n\n<p>Let us run the above code in the console of a browser with the console.dir<em>( ) <\/em>method<em> <\/em>and see what information we get:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh6.googleusercontent.com\/JwhSmSbX9JRe4FbZCvEBdRmV3lx8O6kEo_m600NZ0Ji2Dz0XrStTypbE_u53izpUaBtQCEGFFsS8WQlCBXmDhxmZnC4Sa1m85hjTojCKgBrCiW0Lda93_PEb3D_dsWa34OV2trM=s0\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh6.googleusercontent.com\/JwhSmSbX9JRe4FbZCvEBdRmV3lx8O6kEo_m600NZ0Ji2Dz0XrStTypbE_u53izpUaBtQCEGFFsS8WQlCBXmDhxmZnC4Sa1m85hjTojCKgBrCiW0Lda93_PEb3D_dsWa34OV2trM=s0\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<p>Now, here we can see that the <em>console.dir( ) <\/em>method is7 used to get information about the variables that hold the reference of the function, we can see that both are Closures with different lexical environments, i.e., 10 and 20.&nbsp;<\/p>\n\n\n\n<p>Let\u2019s look into another example to get a better understanding of closures in JavaScript:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/lh3.googleusercontent.com\/jaBKJ3gW8cF_kRMlhIuKmaCVNHnysun0ERwc1U5moZre0WlywH9x1ozjfdOkZEhGTbADoeCx1gxx9Xhhf-7ueIT9D1MstMC_g0SsRIueZ0QxCf1BtoBfUR2nzGC9HHQbUttr_kg=s0\" alt=\"\" title=\"\"><\/figure>\n\n\n\n<p>In the above example, the outer function <em>Counter<\/em> returns the reference of the inner function <em>increase counter ()<\/em>. Here, the function <i>increase counter<\/i> increases the outer variable counter to 1. The <em>Counter( )<\/em> function updates its closures every time it is called. So calling the inner function multiple times will increase the counter by one every time. So, we can say that closures are valid in multiple levels of inner functions as well.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">When to Use Closures in JavaScript?<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">1. Emulating Private Methods<\/h3>\n\n\n\n<p>We generally use closures as access modifiers to give objects&#8217; data a kind of private state. Data privacy is an essential property that helps us to program an interface, not an implementation. Any exposed method defined within the scope of the closure is privileged (accessed by only certain entities).<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">2. Maintaining States Between Function Calls<\/h3>\n\n\n\n<p>Let&#8217;s suppose there is a function that multiplies different values together. One way of doing that is with the help of a global variable because they are available throughout the code. But, there is a drawback! Yes, a variable that is globally accessible can also be modified from anywhere in the code. We can achieve this using closures. Closures help in maintaining as well as capturing the state between different function calls without using a global variable.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">3. Functional Programming<\/h3>\n\n\n\n<p>Currying, which is an important function of functional programming, is also possible due to closures. It occurs when a function returns another function until we completely supply the arguments.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">4. Create Iterators<\/h3>\n\n\n\n<p>Last but not least, creating an iterator. It is fairly easy to create iterators. This is because using closures we can well-preserve the data from the outer scope. Every call creates a new iterator (using closures) with a fixed starting index. Then, at every successive call of the iterator, the next value is returned. However, we should be cautious while using it with jQuery (or other JavaScript events).<\/p>\n\n\n\n<p>Apart from the above-mentioned, you can think of several other ways to use closures according to your needs. You just need to have a good knowledge of scopes and lexical scopes to get the best out of closures.<\/p>\n\n\n\n<p><em>Kickstart your Full Stack Development journey by enrolling in <a href=\"https:\/\/www.guvi.in\/zen-class\/full-stack-development-course\/?utm_source=blog&amp;utm_medium=organic&amp;utm_campaign=Closures-in-JavaScript\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>HCL GUVI\u2019s Full Stack Development Career Program<\/strong><\/a> with placement assistance where you will master the MERN stack (MongoDB, Express.js, React, Node.js) and build interesting real-life projects. This program is crafted by our team of experts to help you upskill and assist you in placements. Alternatively, if you want to explore JavaScript through a self-paced course, try <a href=\"https:\/\/www.guvi.in\/courses\/web-development\/advanced-javascript\/?utm_source=blog&amp;utm_medium=organic&amp;utm_campaign=Closures-in-JavaScript\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>HCL GUVI\u2019s JavaScript self-paced certification course.<\/strong><\/a><\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>The closures are a very useful concept. Beginner JavaScript Programmers often find the concept of closures too overwhelming and skip it altogether. The scope rules, lexical scoping, and nested scopes are the accessibility of variables. The lexical scope allows a function scope to statically access the variables from the outside of the scopes. There can be a function or a block scope. Most of the time people are already using them without actually realizing it. <\/p>\n\n\n\n<p>Closures matter in a code because they allow us to retain the values even after execution, which is a powerful and unique feature in JavaScript that only functions can have. Sometimes, we need to hold onto some values and likely keep them separate from others. So what do you use in that case? simple, A function. Why, though? To keep track of the data over time, with a closure.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">FAQs on Closures of JavaScript<\/h2>\n\n\n<div id=\"rank-math-faq\" class=\"rank-math-block\">\n<div class=\"rank-math-list \">\n<div id=\"faq-question-1689916454825\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Q1. Closures can be used for performing which of the following operations?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Ans<\/strong>. The options are &#8211;<br \/><strong>Maintaining states between function calls<\/strong><br \/><strong>Emulating private methods<\/strong><br \/><strong>Creating iterators<\/strong><br \/><strong>All of the above<\/strong><\/p>\n<p><strong>Correct Answer: <\/strong>(d) All of the above<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1689916554367\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Q2. JavaScript uses which type of scoping?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Ans<\/strong>. The options are &#8211;<br \/><strong>Segmental<\/strong><br \/><strong>Sequential<br \/>Lexical<br \/>Literal<\/strong><\/p>\n<p><strong>Correct Answer: (c) <\/strong>Lexical scoping<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1689916623536\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Q3. Which of the following is mandatory to implement lexical scoping?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Ans<\/strong>. <br \/><strong>Reference the current scope chain<\/strong><br \/><strong>Dereference the current scope chain<\/strong><br \/><strong>Return the value<\/strong><br \/><strong>None of the above<\/strong><\/p>\n<p><strong>Correct Answer: (a) <\/strong>to implement the lexical scoping, the internal state of JavaScript must include a reference to the current scope chain apart from the code of the function.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1689916729211\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Q4. JavaScript is a\/an ______ language?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Ans<\/strong>. <br \/><strong>High-level<\/strong><br \/><strong>Assembly<br \/>Object-oriented<br \/>Object-based<\/strong><\/p>\n<p><strong>Correct Answer: (d)<\/strong> JavaScript is an object-based language. It is not a completely object-oriented language because it does not follow three basic properties of OOPs such as polymorphism, Encapsulation, and Inheritance.<\/p>\n\n<\/div>\n<\/div>\n<div id=\"faq-question-1689916789312\" class=\"rank-math-list-item\">\n<h3 class=\"rank-math-question \">Q5. What will be the output of the following JavaScript code?<\/h3>\n<div class=\"rank-math-answer \">\n\n<p><strong>Ans<\/strong>. <br \/>var\u00a0temp=50;\u00a0\u00a0<br \/>if (temp<strong>><\/strong>100)\u00a0\u00a0<br \/>{\u00a0\u00a0<br \/>document.write(100);\u00a0\u00a0<br \/>}\u00a0\u00a0<br \/>else\u00a0\u00a0<br \/>{\u00a0\u00a0<br \/>document.write(temp);\u00a0\u00a0<br \/>}<\/p>\n<p><strong>100<br \/>0<br \/>50<br \/>Undefined<\/strong><\/p>\n<p><strong>Correct Answer: (c) 50<\/strong>50 is not greater than 100, therefore if the condition fails then else condition will execute. Hence, 50 will be our output.<\/p>\n\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n\n\n<p>So, that was all about Closures in JavaScript. Go ahead and practice umpteen questions and coding challenges around the topic in our specially curated <a href=\"https:\/\/www.guvi.in\/code-kata\/\"><strong>Practice platform CODEKATA<\/strong>. <\/a><\/p>\n\n\n\n<p>Wish to learn every bit of JavaScript? Have the most simplified glance of all the concepts in JavaScript in HCL GUVI Classes. You can join us with a click. <\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><a href=\"https:\/\/www.guvi.in\/zen-class\/full-stack-development-course\/\" target=\"_blank\" rel=\"noreferrer noopener\">Master Tech Courses with 100% Placement Support in ZEN Class From HCL GUVI!<\/a><\/pre>\n\n\n\n<p><a href=\"https:\/\/www.guvi.in\/blog\/\">Find more such informational blogs around the corner and keep reading!<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you&#8217;re a beginner and wondering what are closures in JavaScript, you&#8217;ve come to the right place. In this blog, we&#8217;ll be talking about closures in JavaScript. Let&#8217;s understand more about its history, advantages, and some examples to understand its functioning. They are crucial in functional programming, and hence they\u2019re something that is frequently asked [&hellip;]<\/p>\n","protected":false},"author":9,"featured_media":5287,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[37,429],"tags":[],"views":"5715","authorinfo":{"name":"Archana","url":"https:\/\/www.guvi.in\/blog\/author\/archana\/"},"thumbnailURL":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2021\/09\/image-300x169.png","jetpack_featured_media_url":"https:\/\/www.guvi.in\/blog\/wp-content\/uploads\/2021\/09\/image.png","_links":{"self":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/5286"}],"collection":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/users\/9"}],"replies":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/comments?post=5286"}],"version-history":[{"count":35,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/5286\/revisions"}],"predecessor-version":[{"id":91793,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/posts\/5286\/revisions\/91793"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media\/5287"}],"wp:attachment":[{"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/media?parent=5286"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/categories?post=5286"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.guvi.in\/blog\/wp-json\/wp\/v2\/tags?post=5286"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}