Anonymous functions and closures
Anonymous functions and closures are powerful features in JavaScript that allow for creating more flexible and reusable code.
1. Anonymous function is a function without a name. It can be assigned to a variable or passed as an argument to another function. For example:
let square = function(x) { return x * x; } console.log(square(5)); // Output: 25
In this example, square is an anonymous function assigned to a variable. It takes an argument x and returns the square of that value.
2. Closures are functions that have access to variables in their outer scope, even after the outer function has returned. This is because the inner function maintains a reference to its outer lexical environment. For example:
function outer() { let count = 0; function inner() { count++; console.log(count); } return inner; } let counter = outer(); counter(); // Output: 1 counter(); // Output: 2
In this example, outer returns an anonymous function inner that increments and logs a variable count in its outer scope. outer is called and its result is assigned to counter. When counter is called, it calls inner and increments the count variable, which is maintained in the lexical environment of outer. So each time counter is called, the count variable is incremented and logged to the console.
No Comment! Be the first one.