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 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
How to switch dark and light themes using pure CSS?CSSHow to select multiple values in React dropdown?ReactHow to change value of a span tag using a reference from another div using jQuery?jQueryContent Blocks in SCSS (Sass)SCSSHow to get the full URL of current page in PHP?PHPHow to create a sticky menu pin using CSS?CSSHow to get previous days or next days in PHP?PHPHow to draw an SVG path on scroll using JavaScript?JavaScriptHow to create a link tag button using CSS?CSSReview an intentionally vulnerable plugin in WordPressWordPressHow to display a student’s individual transcript in Colleague?ColleaguePHP __construct() functionPHP