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)
- Function Declaration: A normal function defined using the function keyword.
Program:
function add(a, b) {
return a + b;
}
✔ Can be called before declaration.
- Function Expression: Function stored in a variable.
const multiply = function(a, b) {
return a * b;
};
✔ Cannot be called before definition.
- Arrow Function (ES6): Short and modern syntax. Program:
const subtract = (a, b) => a - b;
✔ Clean and simple
✔ No function keyword needed.
- Anonymous Function: Function without a name.
Program:
setTimeout(function() {
console.log("Hello");
}, 1000);
✔ Mostly used as arguments.
- IIFE (Immediately Invoked Function Expression) Runs immediately after creation.
Program:
(function() {
console.log("Executed immediately");
})();
- 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);
});
- Recursive Function: A function that calls itself.
Program:
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
Top comments (1)
Function expression and storing a function in a variable are two different things. You haven't explained what function expression is.