
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Closures vs Anonymous Functions
In this article, we will learn about JavaScript's closures and anonymous functions. JavaScript is a powerful language that allows developers to write expressive and concise code. Two concepts that often confuse beginners are closures and anonymous functions. While they share some similarities, they serve different purposes and function differently in JavaScript
What is Anonymous Functions?
An anonymous function is simply a function without a name. Anonymous, as the name suggests, allows the creation of a function without any name identifier. It can be used as an argument to other functions, assigned to a variable, or immediately invoked. They are called using the variable name.
Example
This is how JavaScript anonymous functions can be used ?
var func = function() { alert(?This is anonymous'); } func();
Output
Example
Another example can be the following ?
setTimeout(function() { alert('Demo'); }, 3000);
Output
After 3 seconds, an alert box pops up displaying ?
Use Cases of Anonymous Functions
Following are the use cases of anonymous functions ?
-
Callback functions (e.g., event handlers, setTimeout, map, filter, etc.).
-
Function expressions (storing functions in variables).
- Immediately Invoked Function Expressions (IIFE).
What is JavaScript Closures?
In JavaScript all functions work like closures. A closure is a function that uses the scope in which it was declared when invoked. It is not the scope in which it was invoked.
Example
Below is an example of JavaScript closures ?
<!DOCTYPE html> <html> <body> <h2>JavaScript Closures</h2> <script> var p = 20; function a() { var p = 40; b(function() { alert(p); }); } function b(f) { var p = 60; f(); } a(); </script> </body> </html>
Output
An alert message will appear with the value of p ?
Use Cases of Closures
Following are the use cases of closures ?
- Data encapsulation (creating private variables).
- Maintaining state between function calls.
- Function factories (generating customized functions dynamically).
- Event handling and callbacks.
Conclusion
While anonymous functions and closures may seem similar, they serve different purposes in JavaScript. Anonymous functions are unnamed functions often used for short-lived tasks like callbacks. On the other hand, the closures are functions that remember variables from their outer scope, making them useful for encapsulation and maintaining state.