📖 JavaScript Anonymous Functions

Anonymous functions are functions that do not have a name. They are often used as arguments to other functions or assigned to variables. Understanding how to use anonymous functions can help you write more concise and flexible code. Additionally, anonymous functions are commonly used in higher-order functions.

Definition and Syntax

An anonymous function is a function that is declared without any named identifier. It is typically used as an argument to other functions or assigned to a variable.


// Anonymous function assigned to a variable
const greet = function(name) {
    return `Hello, ${name}!`;
};

console.log(greet('Alice')); // Output: Hello, Alice!
        

Examples of Anonymous Functions

Anonymous functions can be used in various contexts. Here are some examples:


// Example 1: Anonymous function as an argument to a higher-order function
setTimeout(function() {
    console.log('This is an anonymous function');
}, 1000);

// Example 2: Anonymous function assigned to a variable
const multiply = function(a, b) {
    return a * b;
};

console.log(multiply(2, 3)); // Output: 6

// Example 3: Anonymous function in an event handler
document.getElementById('myButton').addEventListener('click', function() {
    alert('Button clicked!');
});
        

Use Cases for Anonymous Functions

Anonymous functions are particularly useful in the following scenarios:

Callbacks
Anonymous functions are commonly used as callback functions, which are passed as arguments to other functions and executed at a later time. They are often seen in higher-order functions.
Event Handlers
Anonymous functions are often used as event handlers, which are functions that are executed in response to specific events such as clicks or key presses.
Inline Function Definitions
Anonymous functions can be used to define functions inline, making the code more concise and easier to read.

Putting It Into Action

To see this code in action, create an HTML file and include the following script. This script will define several anonymous functions and use them in different contexts, logging the results to the console.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Anonymous Functions Example</title>
</head>
<body>
    <button id="myButton">Click me</button>
    <script>
        setTimeout(function() {
            console.log('This is an anonymous function');
        }, 1000);

        const multiply = function(a, b) {
            return a * b;
        };

        console.log(multiply(2, 3)); // Output: 6

        document.getElementById('myButton').addEventListener('click', function() {
            alert('Button clicked!');
        });
    </script>
</body>
</html>
        

Challenge

Modify the example to create a new anonymous function that takes two numbers as parameters and returns their sum. Assign this function to a variable and log the results to the console.

Solution


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Anonymous Functions Example</title>
</head>
<body>
    <button id="myButton">Click me</button>
    <script>
        setTimeout(function() {
            console.log('This is an anonymous function');
        }, 1000);

        const multiply = function(a, b) {
            return a * b;
        };

        const sum = function(a, b) {
            return a + b;
        };

        console.log(multiply(2, 3)); // Output: 6
        console.log(sum(2, 3));      // Output: 5

        document.getElementById('myButton').addEventListener('click', function() {
            alert('Button clicked!');
        });
    </script>
</body>
</html>
                        

References