Type of function in JavaScript

Types of Functions in JavaScript with Examples

JavaScript supports various types of functions, each serving different purposes. Let’s go through them one by one with examples.


1. Named Function

A named function has a specified name and can be reused.
🔹 Best used for code reusability.

function greet() {

    console.log("Hello, World!");

}

greet(); // Output: Hello, World!

2. Anonymous Function

A function without a name, usually assigned to a variable.
🔹 Best used in callbacks and event listeners.

const greet = function() {

    console.log("Hello, Anonymous!");

};

greet(); // Output: Hello, Anonymous!

3. Arrow Function (ES6)

A concise way to write functions using =>.
🔹 Best for short functions, callbacks, and this binding.

const add = (a, b) => a + b;

console.log(add(5, 3)); // Output: 8

âš¡ Short Syntax Variants:
✅ Single Parameter:

const square = x => x * x;

console.log(square(4)); // Output: 16

✅ No Parameters:

const sayHello = () => console.log("Hello!");

sayHello(); // Output: Hello!

4. Immediately Invoked Function Expression (IIFE)

A function that runs immediately after being defined.
🔹 Best for preventing variable pollution in the global scope.

(function() {

    console.log("This runs immediately!");

})(); // Output: This runs immediately!

🔹 Arrow function version:

(() => console.log("IIFE with Arrow Function!"))();

// Output: IIFE with Arrow Function!

5. Generator Function (function*)

A function that can pause execution and resume later using yield.
🔹 Best for handling asynchronous operations & infinite sequences.

function* generateNumbers() {

    yield 1;

    yield 2;

    yield 3;

}

const gen = generateNumbers();

console.log(gen.next().value); // Output: 1

console.log(gen.next().value); // Output: 2

console.log(gen.next().value); // Output: 3

6. Higher-Order Function

A function that takes another function as an argument or returns a function.
🔹 Best for functional programming, callbacks, and composition.

function operate(x, y, operation) {

    return operation(x, y);

}

const multiply = (a, b) => a * b;

console.log(operate(3, 4, multiply)); // Output: 12

7. Recursive Function

A function that calls itself to solve a problem.
🔹 Best for problems like factorial, Fibonacci, and tree traversal.

function factorial(n) {

    return n === 0 ? 1 : n * factorial(n - 1);

}

console.log(factorial(5)); // Output: 120

8. Callback Function

A function passed as an argument to another function.
🔹 Best for asynchronous tasks and event handling.

function greet(name, callback) {

    console.log("Hello, " + name);

    callback();

}

greet("John", () => console.log("Callback executed!"));

/*

Output:

Hello, John

Callback executed!

*/

9. Pure Function

A function that always returns the same output for the same input and has no side effects.
🔹 Best for predictable results and functional programming.

function add(a, b) {

    return a + b;

}

console.log(add(2, 3)); // Output: 5

10. Async Function (async/await)

A function that works asynchronously using the await keyword.
🔹 Best for handling Promises and asynchronous operations.

async function fetchData() {

    let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');

    let data = await response.json();

    console.log(data);

}

fetchData();

Comparison Table: Function Types in JavaScript

Function TypeSyntaxUse Case
Named Functionfunction myFunc() {}Code reusability
Anonymous Functionconst func = function() {}Assigning functions to variables
Arrow Functionconst func = () => {}Shorter syntax, this binding
IIFE(function() {})();Avoid global scope pollution
Generator Functionfunction* gen() { yield x; }Pausable function execution
Higher-Order Functionfunction func(f) { f(); }Functional programming
Recursive Functionfunction fact(n) { return n * fact(n-1); }Problems like factorial, Fibonacci
Callback Functionfunction myFunc(cb) { cb(); }Asynchronous tasks
Pure Functionfunction sum(a, b) { return a + b; }Predictable results
Async Functionasync function() { await task(); }Handling Promises

Conclusion

JavaScript provides multiple types of functions for different scenarios.
💡 Use Case Suggestions:

  • Use named functions for readability.
  • Use arrow functions for concise code.
  • Use IIFE to avoid polluting the global scope.
  • Use async/await for asynchronous operations.
  • Use higher-order functions for better function composition.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *