Yogesh Chauhan's Blog

What’s a 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() {
    console.log(message);
  }
  print();
}
greet("Yogesh");
//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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to create a sidebar using pure CSS?CSSHow to Create a Backup From Any Database in SQL?SQL/MySQLHow to remove the Gutenberg Block Library CSS from WordPress?WordPressThe simple difference between var, let and const in JavascriptJavaScriptWhat’s new in WordPress 5.5?WordPressHow to update database configurations in WordPress?WordPressWhat Is a Graph Database?MiscellaneousHow to add Google Static Map using ACF map field?WordPressHow to create ‘share on LinkedIn’ link using just HTML?HTMLHow to create a placeholder loader (throbber) using CSS?CSSJavaScript: how to detect a browser using the user agent?JavaScriptShort-Circuit Evaluation in JavaScriptJavaScript