DEV Community

Cover image for Types of Functions in JavaScript
Ezhil Abinaya K
Ezhil Abinaya K

Posted on

Types of Functions in JavaScript

Types of Functions in Javascript
1. Named Function
A function that has its own name when declared. Itโ€™s easy to reuse and debug because the name shows up in error messages or stack traces.This is the most traditional way to write a function. It has a specific name and can be used (called) anywhere in your code, even before it's defined (called hoisting).

console.log(greet());
function greet() {
  return "Hello!";
}//Hello!

Enter fullscreen mode Exit fullscreen mode

2. Anonymous Function
A function that does not have a name. It is usually assigned to a variable or used as a callback. Since it has no name, it cannot be called directly.

let greet = function() {
  console.log("Hello!");
};
greet();//Hello!
Enter fullscreen mode Exit fullscreen mode

3. Function Expression
A Function Expression is a function that is assigned to a variable and can be invoked using that variable name.

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

console.log(add(2, 3));//5
Enter fullscreen mode Exit fullscreen mode

4. Arrow Function (ES6)
Arrow functions are a compact, streamlined way to write function expressions in JavaScript. Introduced in ES6, they eliminate the need for the function keyword and provide unique rules for scoping. A new way to write functions using the => syntax.
Syntax Variations
Multiple parameters(Single-Line Expression): Wrapped in standard parentheses. Omit the curly braces and return keyword.

const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

Single parameter: Parentheses can be completely omitted.

const square = x => x * x;
Enter fullscreen mode Exit fullscreen mode

Zero parameters: Empty parentheses are strictly required.

const greet = () => "Hello World!";
Enter fullscreen mode Exit fullscreen mode

Multi-line block: Requires curly braces and an explicit return keyword.

const calculateTotal = (price, tax) => {
    const total = price + tax;
    return total;
};

Enter fullscreen mode Exit fullscreen mode

5. Immediately Invoked Function Expression (IIFE)
An Immediately Invoked Function Expression (IIFE) is simply a JavaScript function that runs automatically the exact moment it is defined.Normally, a function runs only when it is called.An IIFE runs automatically when the JavaScript engine reads it (compiles it).Everything inside an IIFE is private to that function.Variables inside an IIFE cannot be accessed from outside.

(function() {
  console.log("I run immediately!");
})();// I run immediately

Enter fullscreen mode Exit fullscreen mode

6. Callback Functions
A JavaScript callback is a function passed as an argument to another function, which is then executed (or "called back") at a later point in time to complete a specific task.
Types of Callbacks
Synchronous Callbacks
Synchronous code executes line by line, one statement at a time. The next statement waits until the current statement finishes.

console.log("Start");
console.log("Middle");
console.log("End");
//Start 
Middle 
End
Enter fullscreen mode Exit fullscreen mode

Real Life Examples for Synchronous
Imagine ATM machine.
Insert Card -->Enter Pin -->Select Amount --> Get Money
Here, to move to the next step, the current step must be completed first. This is called synchronous execution.
Asynchronous Callbacks:
Asynchronous callbacks are executed at a later time, allowing the main program to continue running without waiting.This is essential for preventing the application from freezing during long-running tasks like network requests.In simple words, Asynchronous code allows other code to run without waiting for a time-consuming task to finish.

console.log("Start");

setTimeout(() => {
    console.log("Middle");
}, 2000);

console.log("End");
//Start
End
Middle
Enter fullscreen mode Exit fullscreen mode

Here , Start prints.setTimeout() starts a timer (2 seconds).JavaScript doesn't wait.End prints immediately.After 2 seconds, Middle prints.
Real Life Examples for Asynchronous Callbacks
1.File Download: Click Download -->Download running... -->Meanwhile use browser normally
This is Asynchronous.
2.Login Request:Click Login -->Server checks username/password-->Response comes later
This is Asynchronous.
Callback Function General Syntax

function mainFunction(callback) {
    callback();
}

function callbackFunction() {
    // code
}

mainFunction(callbackFunction);
Enter fullscreen mode Exit fullscreen mode

Examples for callback

function display(callback) {
    callback();
}

function greet() {
    console.log("Hello");
}

display(greet);//Hello
Enter fullscreen mode Exit fullscreen mode

display โ†’ Main function
greet โ†’ Callback function
A callback function is a function passed as an argument to another function and executed later.

function welcome(callback) {
    console.log("Welcome User");
    callback();
}

function thankYou() {
    console.log("Thank You");
}

welcome(thankYou);//Welcome User
                  //Thank You
Enter fullscreen mode Exit fullscreen mode

Real-Life Callback Example
Suppose you order food from a restaurant:

  • You place the food order.
  • You give your phone number.
  • When the food is ready, the restaurant calls you.

Here:
Food order = Main function
Phone number = Callback
You provide your phone number now, but it is used later when the task (preparing the food) is completed.
This is similar to a callback function in JavaScript: you pass a function now, and it is executed later after a specific task is finished.

function orderFood(callback) {
    console.log("Food is being prepared...");
    callback();
}

function callCustomer() {
    console.log("Food is ready!");
}

orderFood(callCustomer);//Food is being prepared...
                       //Food is ready!
Enter fullscreen mode Exit fullscreen mode


References
https://www.geeksforgeeks.org/javascript/functions-in-javascript/
https://www.w3schools.com/js/js_callback.asp

Top comments (6)

Collapse
 
vigneshwaran_v profile image
Vigneshwaran V

good explanation with right examples, thank you ๐Ÿ˜Š for that memes and all.

Collapse
 
ezhil_abinayak_e38eec8fb profile image
Ezhil Abinaya K

Thnx alot๐Ÿ˜

Collapse
 
annapoo profile image
Annapoorani Kadhiravan

Amazing ! Great efforts ๐Ÿ‘Œ

Collapse
 
ezhil_abinayak_e38eec8fb profile image
Ezhil Abinaya K

Thnx alots๐Ÿ˜

Collapse
 
kamalesh_ar_6252544786997 profile image
Kamalesh AR

Nice memes๐Ÿ˜Š!. Easy to understand your explanation ๐Ÿ‘๏ธ

Collapse
 
ezhil_abinayak_e38eec8fb profile image
Ezhil Abinaya K

Thnx alots๐Ÿ˜