dots Created with Sketch.
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 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

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
For Each Loop in Swift for BeginnersSwiftHow to pass arguments in SCSS function?SCSSDebugging in WordPress Part 2: WP_DEBUG_LOG and WP_DEBUG_DISPLAYWordPressHow to show widgets on the Appearance tab in WordPress?WordPressHow to check if a link has http or https in it in JavaScript?JavaScriptWhat’s a repository on Github?MiscellaneousHow to remove border from :visited image, link or button?CSSThe Lending Club Analysis using Logistic Regression and Random Forest in RStudioMiscellaneousThe Differences Between HAVING Clause and WHERE Clause in SQLSQL/MySQLWhat does it mean by Continuous Integration, Continuous Delivery and Continuous Deployment?MiscellaneousHow to define visibility for a property in PHP?PHPHow to create a sticky menu pin using CSS?CSS