DEV Community

Praveen Kumar K
Praveen Kumar K

Posted on

What is Function and it's types?

A function is a block of code designed to perform a specific task. It runs only when it is called (invoked), and it helps make code reusable, clean, and easy to manage.

Program:

function greet(name) {
return "Hello " + name;
}

console.log(greet("Praveen"));

✔ Output:

Hello Praveen

Types of Functions (in JavaScript)

  1. Function Declaration: A normal function defined using the function keyword.

Program:

function add(a, b) {
return a + b;
}
✔ Can be called before declaration.

  1. Function Expression: Function stored in a variable.

const multiply = function(a, b) {
return a * b;
};
✔ Cannot be called before definition.

  1. Arrow Function (ES6): Short and modern syntax. Program:

const subtract = (a, b) => a - b;
✔ Clean and simple
✔ No function keyword needed.

  1. Anonymous Function: Function without a name.

Program:

setTimeout(function() {
console.log("Hello");
}, 1000);
✔ Mostly used as arguments.

  1. IIFE (Immediately Invoked Function Expression) Runs immediately after creation.

Program:

(function() {
console.log("Executed immediately");
})();

  1. Callback Function:

A function passed as an argument to another function.

Program:

function processUser(name, callback) {
callback(name);
}

processUser("Praveen", function(name) {
console.log("Hello " + name);
});

  1. Recursive Function: A function that calls itself.

Program:

function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Function expression and storing a function in a variable are two different things. You haven't explained what function expression is.