

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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>
- Related Questions & Answers
- JavaScript Encapsulation using Anonymous Functions
- Anonymous Wrapper Functions in JavaScript
- When to use anonymous JavaScript functions?
- PHP Anonymous functions
- Regular functions vs Arrow functions in JavaScript?
- What are Self-Invoking Anonymous Functions in JavaScript?
- How to pass arguments to anonymous functions in JavaScript?
- What is a typical use case for JavaScript anonymous functions?
- Fat vs concise arrow functions in JavaScript
- What is the difference between anonymous and inline functions in JavaScript?
- Does use of anonymous functions affect performance?
- The Anonymous Functions in Python
- How do JavaScript closures work?
- What are JavaScript Function Closures?
- What are Closures in JavaScript?
Advertisements