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

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
for @each loop in SCSSSCSSHow to make flexbox items of the same size?CSSHow to create ‘share on LinkedIn’ link using just HTML?HTMLHow different is Handling Events in React vs HTML DOM?ReactHow to Write Complex Search Queries in SQL?SQL/MySQLCROSS JOIN in PostgresPostgresSolution to pod install fails with json error on Mac OS X 10.15 (or Mac OS Catalina)MiscellaneousThe simple difference between var, let and const in JavascriptJavaScriptColleague UI Basics: The Context AreaColleagueHow to Pop an Alert Box in PHP?JavaScriptPagination in CSS with multiple examplesCSSHow to Find the Highest (or Lowest) Number in an Array in JavaScript?JavaScript