- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Anonymous Functions
Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. They are called using the variable name:
This is how JavaScript anonymous functions can be used:
var func = function() { alert(‘This is anonymous'); } func();
Another example can be the following:
setTimeout(function() { alert('Demo'); }, 3000);
JavaScript Closures
In JavaScript, all functions work like closures. A closure is a function, which uses the scope in which it was declared when invoked. It is not the scope in which it was invoked.
Here’s an example:
<!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>
Advertisements