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() {
//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
Steps to Install Microsoft SQL Server on a MacOSSQL/MySQLHow to vertically align a html radio button to it’s label?CSSLIMIT and OFFSET in PostgresPostgresKilling A Project Part 4: What Would Be Your Top 3 Priorities For Planning The Cancellation?MiscellaneousHow to center an image horizontally and vertically?CSS3 JavaScript methods to use when you want to go back and forth in historyJavaScript3 ways to pass a variable in url() function in SCSS (Sass)SCSSHow to use [] (square brackets) function in Envision Basic?Envision Basicperspective property in CSSCSSHow to Check If a Variable is an Integer, a Float, a Number, NaN, an Infinite or a Numeric in PHP?PHPIntroduction to Angular modules Part 3: NgModules vs JavaScript modules and Angular librariesAngularHow to Write Complex Search Queries in SQL?SQL/MySQL