Thursday, September 19, 2024

Anonymous Functions in JavaScript

 


1. Anonymous Functions

Anonymous functions are functions defined without a name. In JavaScript, anonymous functions are powerful features and can be used in several contexts. It is common in JavaScript to find an anonymous function assigned to a variable, passed as an argument to another function, declared to handle an event, or a callback to array methods such as map, filter, etc.


2. Benefits of Using Anonymous Functions

Anonymous functions have more concise syntax and are often more readable, especially after launching arrow functions.


3. Contexts of Use of Anonymous Functions

The following tables show the main contexts in which anonymous functions are used:


Usage of Anonymous Function

Code Snippet

Code Output

Assigned to a Variable

let sayHello = function() {

console.log("Hello, world!");

};

sayHello();


let sum = function(a, b) {

return a+b;

};

console.log("Result of addition is:", sum(4, 7));


Hello, world!

11

Argument to Another Function

setTimeout(function() {

console.log("You waited two seconds to get this message.");

}, 2000);


You waited two seconds to get this message.

Immediately Invoked Function Expression (IIFE)

(function() {

console.log("You get this message immediately.");

})();


You get this message immediately.

Callback in Event Handlers

<button id="button1">Mouse over me!</button>

<script>

document.getElementById("button1").addEventListener("mouseover", function() {

console.log("Thanks for hovering over me!");

});

</script>


Thanks for hovering over me!

In Array Methods (filter, map, etc)

let numbers = [10, 12, 345, 63, 15];

let evenNumbers = numbers.filter(function(num) {

return num % 2 === 0;

});

console.log(evenNumbers);


[10, 12]

Arrow Function Expression

let nExp = (a, n) => a ** n;

console.log(nExp(5, 4));


625


No comments:

Post a Comment

Blog Posts

Enhancing Performance of Java-Web Applications

Applications built with a Java back-end, a relational database (such as Oracle or MySQL), and a JavaScript-based front-end form a common and...