- 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 simply a function that does not have a name (identifier) attached to it.
- While standard function declarations like
function doSomething() {}are "hoisted" and available throughout your script, anonymous functions are typically created as part of an expression and are often assigned to variables or passed directly into other functions.
Syntax (Function Expression):
const variableName = function(parameter1, parameter2, /* ... */) {
// Code to be executed
};
- variableName: This is the constant or variable that stores the function reference. You use this variable name to invoke the function later.
- parameter1, parameter2, ...: These act as placeholders for the data you pass into the function, just like a standard named function.
Why it is Used:
- Encapsulation and Scoping: They help prevent "polluting" the global namespace. If you only need a piece of logic in one specific place, giving it a global name is unnecessary and can lead to naming conflicts.
- Callback Mechanisms: JavaScript is heavily reliant on callbacks (functions passed as arguments). Anonymous functions allow you to write that logic inline, making the code more readable and localized.
- Functional Programming: They are the backbone of methods like
.map(),.filter(), and.reduce(), where you transform data on the fly.
Example:
// Assigning an anonymous function to a variable
const greet = function(name) {
console.log('Hello, ' + name + '!');
};
// Calling the function using the variable name
greet('John'); // Output: Hello, John!
const when assigning an anonymous function to a variable. This ensures the function reference isn't accidentally overwritten later in your code, providing more predictable behavior.
Anonymous Function as Argument:
In real-world development, you’ll rarely see anonymous functions assigned to variables compared to how often they are used as callbacks. They are perfect for one-off tasks like handling a button click or running a timer.
// Using an Anonymous Function inside a timer
setTimeout(function() {
console.log('This message appears after a 2-second delay.');
}, 2000);
// Using an Anonymous Function to iterate over an array
const prices = [10, 20, 30];
const discounted = prices.map(function(price) {
return price * 0.9; // Apply 10% discount
});
console.log(discounted); // [9, 18, 27]
Immediately Invoked Function Expression (IIFE):
An IIFE (pronounced "iffy") is a pattern where an anonymous function is defined and executed at the exact same moment. This was historically used to create private scopes before JavaScript had let, const, and modules.
// The outer parentheses turn the function into an expression
// The trailing () executes it immediately
(function() {
const temporarySecret = "I am hidden from the global scope";
console.log('IIFE executed!');
})();
ES6 Arrow Function:
Modern JavaScript introduced Arrow Functions (=>), which are essentially a more concise syntax for anonymous functions. They are now the standard for most development work because they handle the this keyword more intuitively.
// Traditional Anonymous Function
const add = function(a, b) {
return a + b;
};
// Modern ES6 Arrow Function (Concise version)
const addNumbers = (a, b) => a + b;
console.log(addNumbers(3, 4)); // Output: 7
this often gets confused.
Summary
- Nameless Logic: Anonymous functions provide a way to define logic without cluttering your code with names you'll only use once.
- Portability: They are ideally suited for callbacks, allowing you to pass functionality directly into methods like
setTimeoutorfetch. - IIFEs: Use them for immediate execution and local scoping to keep your variables private.
- Evolution: Arrow functions are the modern successor to the traditional anonymous function, offering cleaner syntax and better scope management.