- JS Introduction
- JS Introduction
- JS Comments
- JS Variables
- JS Datatypes
- JS Operators
- JS Type Conversions
- JS Control Flow
- JS Comparisons
- JS If else
- JS If else Ladder
- JS Ternary Operator
- JS Switch
- JS For Loop
- JS For In
- JS For Of
- JS While
- JS Do While
- JS Break & Continue
- JS Functions
- JS Function Declaration
- JS Function Parameters
- JS Return Statement
- JS Function Expressions
- JS Anonymous Functions
- JS Objects
- JS Objects
- JS Object Methods
- JS Object Constructors
- JS Object Destructuring
- JS Object Prototypes
- JS Map, Filter & Reduce
- JS ES6
- JS ES6
- JS let and const
- JS Arrow Functions
- JS Template Literals
- Destructuring Assignment
- JS Spread Operator
- JS Default Parameters
- JS Classes
- JS Inheritance
- JS Map
- JS Set
- JS Async
- JS Callbacks
- JS Asynchronous
- JS Promises
- JS Async/Await
- JS HTML DOM/BOM
- JS Document Object
- JS getElementbyId
- getElementsByClassName
- JS getElementsByName
- getElementsByTagName
- JS innerHTML
- JS outerHTML
- JS Window Object
- JS History Object
- JS Navigator Object
- JS Screen Object
JavaScript Anonymous Functions
- An anonymous function is a function without a name.
- It is often created using a function expression and is useful for short-term or situational usage.
Syntax (Function Expression):
const variableName = function(parameter1, parameter2, /* ... */) {
// Code to be executed
};
- variableName: The variable that holds the anonymous function.
- parameter1, parameter2, ...: The parameters that the anonymous function accepts.
Why it is Used:
- Temporary Usage: Useful when a function is needed for a specific task and won't be reused elsewhere.
- Function as Argument: Frequently used as arguments to higher-order functions or event handlers.
Example:
// Anonymous Function as a Function Expression
const greet = function(name) {
console.log('Hello, ' + name + '!');
};
// Calling the Anonymous Function
greet('John'); // Output: Hello, John!
Anonymous Function as Argument: Anonymous functions are commonly used as arguments to functions like setTimeout, map, filter, etc.
// Using Anonymous Function as an Argument
setTimeout(function() {
console.log('This function will be executed after 2 seconds.');
}, 2000);
Immediately Invoked Function Expression (IIFE): An IIFE is an anonymous function that is immediately executed after being defined.
// IIFE Example
(function() {
console.log('This is an IIFE.');
})();
ES6 Arrow Function: In ES6 and later versions, arrow functions provide a concise way to create anonymous functions.
// ES6 Arrow Function
const addNumbers = (a, b) => a + b;
console.log(addNumbers(3, 4)); // Output: 7
Summary
- Anonymous functions are functions without a name, often created using function expressions.
- They are useful for short-term tasks, as arguments to other functions, or for immediate execution using IIFE.
- Arrow functions in ES6 provide a concise syntax for creating anonymous functions.