자바스크립트 익명 함수(Anonymous Function)

In JavaScript, functions are a fundamental building block of the language. They allow us to encapsulate blocks of code into reusable units, making our code more modular and maintainable.

One type of function that we frequently encounter in JavaScript is the anonymous function. As the name suggests, an anonymous function is a function that doesn’t have a name identifier associated with it. Instead, it is defined inline as an expression.

Syntax

The syntax of an anonymous function in JavaScript is as follows:

(function() {
  // code here
})();

In this syntax, we define an anonymous function using the function keyword, followed by an open parenthesis (, and then a closing parenthesis ). This set of parentheses is immediately followed by another set of parentheses () which is used to invoke or execute the anonymous function.

Usage

Anonymous functions have several use cases in JavaScript. Let’s explore a few:

1. Immediately Invoked Function Expression (IIFE)

One common use of anonymous functions is to create an immediately invoked function expression (IIFE). This is a way to execute a function immediately after it is defined. Here’s an example:

(function() {
  console.log("IIFE executed!");
})();

In this example, we define an anonymous function and immediately invoke it using the second set of parentheses () at the end. The code inside the function will be executed immediately when the script runs.

2. Callback Functions

Anonymous functions are often used as callback functions, which are functions passed as arguments to another function, to be executed at a later time or in response to an event. Here’s an example with the setTimeout function:

setTimeout(function() {
  console.log("Callback function executed after 2 seconds");
}, 2000);

In this example, we pass an anonymous function as the first argument to setTimeout. The code inside the anonymous function will be executed after a delay of 2 seconds.

3. Event Handlers

Anonymous functions are commonly used as event handlers for DOM events. For instance, when a button is clicked, we can define an anonymous function as the event handler to perform a specific action. Here’s an example:

document.getElementById("myButton").addEventListener("click", function() {
  console.log("Button clicked!");
});

In this example, we define an anonymous function as the event handler for the click event of a button with the id "myButton". When the button is clicked, the code inside the anonymous function will be executed.

Benefits

There are a few benefits to using anonymous functions:

Conclusion

Anonymous functions are a powerful feature in JavaScript that allows us to write more modular and maintainable code. They have various use cases, including immediately invoked function expressions, callback functions, and event handlers. By understanding how to use anonymous functions effectively, we can leverage their benefits and write cleaner and more efficient code.