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 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
URL paths in DrupalDrupalHow to show slider value in HTML5 range input using JavaScript?HTMLJavaScript Input Validation Theme Park Example using throw StatementJavaScriptHow to link/add CSS file to HTML Document?CSSHow to calculate elapsed time in JavaScript?JavaScriptVariables scope and shadowing in SCSS (Sass)SCSSHow to swap images on hover using CSS?CSSHow to clean up after a plugin uninstall in WordPress?WordPressIs Software Really Eating The World? I don’t think soMiscellaneousAttributes and Properties in JavaScript and HTMLHTMLHow to animate list items using CSS and JavaScript?CSSHow to CREATE TABLE in SQL with and without using Another Table?SQL/MySQL