DEV Community

Madhan Raj
Madhan Raj

Posted on

Functions in Javascript

*Type of Functions *

Here the main 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.

function greet() {
  return "Hello!";
}
console.log(greet());
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.

const greet = function() {
  return "Hi there!";
};
console.log(greet());
Enter fullscreen mode Exit fullscreen mode

3. Function Expression
When you assign a function (can be named or anonymous) to a variable. The function can then be used by calling that variable.

const add = function(a, b) {
  return a + b;
};
console.log(add(2, 3));
Enter fullscreen mode Exit fullscreen mode

4. Arrow Function (ES6)

A new way to write functions using the => syntax. They are shorter and do not have their own this binding, which makes them useful in some cases.

const square = n => n * n;
console.log(square(4));
Enter fullscreen mode Exit fullscreen mode

5. Immediately Invoked Function Expression (IIFE)
IIFE functions are executed immediately after their definition. They are often used to create isolated scopes.

(function () {
    console.log("This runs immediately!");
})();
Enter fullscreen mode Exit fullscreen mode

6. Async Function
Functions that handle asynchronous tasks. Declared with async, they return a Promise, and you can use await inside them to pause until another Promise resolves.

async function fetchData() {
  return "Data fetched!";
}
fetchData().then(console.log);
Enter fullscreen mode Exit fullscreen mode

7.Pure Functions
Pure functions return the same output for the same inputs and do not produce side effects. They do not modify state outside their scope, such as modifying global variables, changing the state of objects passed as arguments, or performing I/O operations.

function pureAdd(a, b) {
    return a + b;
}

console.log(pureAdd(2, 3));
Enter fullscreen mode Exit fullscreen mode

Callback Functions

Constructor Function

Generator Function
Recursive Function
Higher-Order Function
Nested Functions
Rest Parameter Function
[TBH]

Reference
https://www.geeksforgeeks.org/javascript/functions-in-javascript/

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ
  • Function expression and assigning a function to a variable are two different things
  • The function stored in greet in your anonymous function example is NOT anonymous - see here
  • It's arguable that the pure function you show is not really pure - there are arguments you can pass in that will produce different results every time - and even induce side effects. Due to the way the language works, it's actually quite difficult to write a 'true' pure function in JS.