Câu hỏi phỏng vấn Javascript
Câu hỏi

What's a typical use case for anonymous functions?

Câu trả lời

Anonymous functions, also known as lambda functions or function literals, are functions defined without a name and are typically used in contexts where a function is required temporarily and only in a specific place within a program. Here are some typical use cases for anonymous functions in JavaScript:

  1. Callbacks: Anonymous functions are often used as callback functions, which are executed after a certain action is completed. For example, they are passed as arguments to other functions that can be asynchronous, such as timers or event handlers[1][2][4].

    javascript Copy
    setTimeout(function() {
        console.log("This is a callback function executed after 1 second");
    }, 1000);
  2. Event Handlers: They are used to define actions that should be taken when a certain event occurs, such as clicks or key presses. Since these functions are generally used only once, there is no need to name them[4].

    javascript Copy
    document.addEventListener("click", function() {
        console.log("The document was clicked");
    });
  3. Immediately Invoked Function Expressions (IIFEs): Anonymous functions are used to create scopes and avoid polluting the global namespace. This is useful in situations where you want to isolate parts of the code to improve maintainability and reduce conflicts in the global scope[1][2].

    javascript Copy
    (function() {
        var localVar = "This variable is local to the IIFE";
        console.log(localVar);
    })();
  4. Array Methods: Functions like forEach, map, filter, etc., which are part of the Array prototype, often use anonymous functions to ...

middle

middle

Gợi ý câu hỏi phỏng vấn

junior

What is Callback Hell and what is the main cause of it? Related To: Node.js

middle

When should we use generators in ES6?

junior

What does use strict do?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào