Different Type of Modern Function in JavaScript

JavaScript has a modern function to make use of advanced methods like the Arrow function, Async/Await and Anonymous functions. I will see some examples here. Let's start with Simple and general Traditional function examples.

Code Example

Console

Anonymous function

This is a function without having a name, also preferred for a short period of time, being in use, and in an Event handler function. Let's have some examples of Immediately Invoked Function Expression (IIFE) and Event handler

1. IIFE

(function() {
    console.log("immediate function !\");
})();

2. Event Handlers

document.getElementById("Button").addEventListener("click", function() {
    alert("Button was clicked!");
});

Async/Await Functions

Async and await function example here. It will wait for a promise and return the response. The Async method will come with the await keyword.

 
function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const data = "Data fetched!";
            resolve(data);
        }, 2000);
    });
}

async function getData() {
    try {
        console.log("Fetching data...");
        const result = await fetchData();
        console.log(result); //"Data fetched!"
    } catch (error) {
        console.error("Error fetching data:", error);
    }
}

//Call the async function
getData();

Arrow function

Arrow Functions are  Introduced in the ES6 version, its way short syntax method expression.

const greet = () => {
    console.log("Hello!");
};

Up Next
    Ebook Download
    View all
    Learn
    View all