DEV Community

Athithya Sivasankarar
Athithya Sivasankarar

Posted on

Types of Functions in JavaScript

1. Function Declaration

This is the basic way to create a function.

Example:

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

sayHello();
Enter fullscreen mode Exit fullscreen mode

Output:

Hello

2. Function Expression

Here, the function is stored in a variable.

Example:

const sayHello = function() {
    console.log("Hello");
};

sayHello();
Enter fullscreen mode Exit fullscreen mode

Output:

Hello

3. Arrow Function (Lambda)

Short and modern way to write functions.

Example:

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

sayHello();
Enter fullscreen mode Exit fullscreen mode

Output:

Hello

4. Anonymous Function

Function without a name.

Example:

const greet = function() {
  return "Hi there!";
};

console.log(greet());
Enter fullscreen mode Exit fullscreen mode

Output:

Hi there!

5. Callback Function

A function passed inside another function.

Example:

function greet(name, fun) {
    fun(name);
}

greet("Ram", function(name) {
    console.log("Hello " + name);
});
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Ram

6. IIFE (Immediately Invoked Function)

Runs immediately after writing.

Example:

(function() {
    console.log("Run now");
})();
Enter fullscreen mode Exit fullscreen mode

Output:

Run now

7. Constructor Function

Used to create objects.

Example:

function Person(name) {
    this.name = name;
}

let p1 = new Person("Ram");
console.log(p1.name);
Enter fullscreen mode Exit fullscreen mode

Output:

Ram

8. Generator Function

Used to return values one by one.

Example:

function* num() {
    yield 1;
}

let n = num();
console.log(n.next().value);
Enter fullscreen mode Exit fullscreen mode

Output:

1

Reference

Top comments (0)