YogeshChauhan . com

What’s Closure in JavaScript?

in JavaScript on April 22, 2021

Closure concept becomes clear when you understand Lexical scoping.

Closure (usually an inner function) enables access to the outer function’s scope.

Just like this following example where message is a local variable and print function is a closure that uses message variable which is declared in the parent function.

function greet(a) {
  var message = 'Hello ' + a;
  function print() {
//Hello Yogesh

The concept of Closure aligns with the object-oriented programming. In OOP, objects let you link data with methods.

JavaScript doesn’t have a native way of creating private methods so Closure comes to the rescue.

Closure lets you imitate private methods just like you can create private methods in Java.

Creating private methods is a good way to restrict your code and also managing your global namespace.

MDN has few examples explaining the private methods using Closure. Check that out.

If you think you really don’t need Closures (or functions inside functions), don’t bother doing so. It will affect your JavaScript performance and memory consumption.


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to uninstall Cocoapods from the Mac OS? #4 How to add Read More Read Less Button using JavaScript? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

May 5 Use inline if to make a shorter conditional syntax in React May 4 What is Conditional Rendering in React? May 3 How does @extend rule work in SCSS (Sass)? May 2 How different is Handling Events in React vs HTML DOM? May 2 How to create bouncing balls using HTML canvas and JavaScript? Apr 30 HTML canvas methods

You might also like these

Values and Types Basics in JavaScriptJavaScripttransform-origin Property in CSSCSSHow to change value of a span tag using a reference from another div using jQuery?jQueryHow to Install PHP Laravel in MacOS Catalina?PHPShort-Circuit Evaluation in JavaScriptJavaScriptThe :last-of-type selectorCSSHow to add Lifecycle Methods to a Class in React?ReactThe order Property in Flex Items in CSSCSSRelative Length Units in CSSCSSNew to ┬áDrupal? Here’s What You Need to KnowDrupalThe Difference Between the echo and print Commands in PHPPHPHow to control file extensions with an .htaccess file?Misc