In JavaScript, functions are fundamental building blocks used to perform a specific task or calculate a value. They are first-class citizens, meaning they can be:
- Stored in variables- Functions can be assigned to variables.
- Passed as arguments - Functions can be passed as arguments to other functions.
- Returned from other functions - Functions can be returned from other functions.
- Created dynamically - Functions can be created dynamically during runtime.
Types of Functions in JavaScript:
-
Named Functions:
- Function Declaration:
function add(a, b) { return a + b; }
-
Anonymous Functions:
- Function Expression:
const multiply = function(a, b) { return a * b; };
-
Arrow Functions (ES6+):
- Arrow functions provide a concise syntax, especially for short functions.
const square = (x) => x * x;
-
IIFE (Immediately Invoked Function Expression):
- Functions that are executed immediately after being created.
(function() { // code here })();
-
Constructor Functions:
- Used to create objects with a shared prototype.
function Person(name, age) { this.name = name; this.age = age; } const person = new Person('Alice', 30);
-
Generator Functions (ES6+):
- Functions that can be paused and resumed.
function* generator() { yield 1; yield 2; yield 3; }
-
Higher-Order Functions:
- Functions that take other functions as arguments or return them.
function higherOrderFunction(func) { return func(2, 3); } function multiply(a, b) { return a * b; } higherOrderFunction(multiply); // Returns 6
-
Callback Functions:
- Functions passed as arguments to another function to be executed later.
function fetchData(callback) { // Fetch data asynchronously const data = fetchDataFromServer(); callback(data); } function process(data) { // Process the fetched data console.log(data); } fetchData(process);
-
Recursive Functions:
- Functions that call themselves within their definition.
function factorial(n) { if (n === 0 || n === 1) { return 1; } else { return n * factorial(n - 1); } }
These different types of functions in JavaScript offer flexibility and are used in various scenarios based on their specific characteristics and functionalities.