Types of functions
In JavaScript, functions are blocks of code designed to perform a particular task. They can be defined in various ways, each serving different use cases. Here's an overview of different types of functions in JavaScript along with examples:
1. Function Declarations
A function declaration defines a function with a specified name.
function greet() {
console.log("Hello, World!");
}
greet(); // "Hello, World!"
2. Function Expressions
A function expression defines a function inside an expression. These can be named or anonymous.
// Anonymous function expression
let greet = function() {
console.log("Hello, World!");
};
greet(); // "Hello, World!"
// Named function expression
let greet = function greetFunction() {
console.log("Hello, World!");
};
greet(); // "Hello, World!"
3. Arrow Functions
Arrow functions provide a shorter syntax for writing functions. They do not have their own this
, arguments
, super
, or new.target
bindings.
let greet = () => {
console.log("Hello, World!");
};
greet(); // "Hello, World!"
// Arrow function with parameters
let add = (a, b) => a + b;
console.log(add(2, 3)); // 5
4. Immediately Invoked Function Expressions (IIFE)
An IIFE is a function that runs as soon as it is defined.
(function() {
console.log("Hello, World!");
})(); // "Hello, World!"
5. Higher-Order Functions
A higher-order function is a function that takes another function as an argument, returns a function, or both.
function greet(name) {
return function(message) {
console.log(message + ", " + name);
};
}
let greetAlice = greet("Alice");
greetAlice("Hello"); // "Hello, Alice"
6. Callback Functions
A callback function is a function passed into another function as an argument to be executed later.
function fetchData(callback) {
// Simulate data fetching
setTimeout(() => {
callback("Data fetched");
}, 1000);
}
function displayData(data) {
console.log(data);
}
fetchData(displayData); // "Data fetched" (after 1 second)
7. Generator Functions
A generator function returns a generator object, which can be used to control the execution of the function.
function* generateNumbers() {
yield 1;
yield 2;
yield 3;
}
let generator = generateNumbers();
console.log(generator.next().value); // 1
console.log(generator.next().value); // 2
console.log(generator.next().value); // 3
8. Async Functions
Async functions allow for asynchronous, promise-based behavior to be written in a cleaner, more understandable way.
async function fetchData() {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
let data = await response.json();
console.log(data);
}
fetchData();
9. Constructor Functions
Constructor functions are used to create objects. They are defined using a capitalized function name and are called with the new
keyword.
function Person(name, age) {
this.name = name;
this.age = age;
}
let alice = new Person("Alice", 30);
console.log(alice.name); // "Alice"
console.log(alice.age); // 30
10. Methods
Methods are functions that are properties of an object.
let person = {
name: "Alice",
greet: function() {
console.log("Hello, " + this.name);
}
};
person.greet(); // "Hello, Alice"
11. Recursive Functions
A recursive function calls itself in order to solve a problem.
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
12. Rest Parameters and Default Parameters
Rest parameters allow you to represent an indefinite number of arguments as an array. Default parameters allow you to specify default values for parameters.
function sum(...numbers) {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
function greet(name = "Guest") {
console.log("Hello, " + name);
}
greet(); // "Hello, Guest"
greet("Alice"); // "Hello, Alice"
13. Closures
A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope.
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log("Outer Variable: " + outerVariable);
console.log("Inner Variable: " + innerVariable);
};
}
let newFunction = outerFunction("outside");
newFunction("inside");
// Output:
// Outer Variable: outside
// Inner Variable: inside
14. Function Hoisting
In JavaScript, function declarations are hoisted to the top of their containing scope, meaning they can be called before they are defined in the code.
sayHello(); // "Hello!"
function sayHello() {
console.log("Hello!");
}
However, function expressions (including arrow functions) are not hoisted in the same way.
sayGoodbye(); // TypeError: sayGoodbye is not a function
var sayGoodbye = function() {
console.log("Goodbye!");
};
15. Function Binding
The bind()
method creates a new function that, when called, has its this
keyword set to a provided value.
let person = {
name: "Alice",
greet: function() {
console.log("Hello, " + this.name);
}
};
let greetAlice = person.greet.bind(person);
greetAlice(); // "Hello, Alice"
16. Function Call and Apply
The call()
and apply()
methods are used to invoke functions with a specified this
value and arguments.
- call(): Passes arguments separately.
function greet() {
console.log("Hello, " + this.name);
}
let person = { name: "Alice" };
greet.call(person); // "Hello, Alice"
- apply(): Passes arguments as an array.
function greet(greeting) {
console.log(greeting + ", " + this.name);
}
let person = { name: "Alice" };
greet.apply(person, ["Hi"]); // "Hi, Alice"
17. Function Currying
Currying is the process of transforming a function that takes multiple arguments into a series of functions that each take a single argument.
function multiply(a) {
return function(b) {
return a * b;
};
}
let double = multiply(2);
console.log(double(5)); // 10
console.log(multiply(3)(4)); // 12
18. Partial Application
Partial application is similar to currying but allows you to fix a number of arguments to a function, producing another function.
function add(a, b) {
return a + b;
}
function partialAdd(a) {
return function(b) {
return add(a, b);
};
}
let addFive = partialAdd(5);
console.log(addFive(10)); // 15
19. Function Composition
Function composition is the process of combining two or more functions to produce a new function.
function addOne(x) {
return x + 1;
}
function double(x) {
return x * 2;
}
function compose(f, g) {
return function(x) {
return f(g(x));
};
}
let addOneThenDouble = compose(double, addOne);
console.log(addOneThenDouble(5)); // 12
20. Named Function Expressions
Named function expressions can be beneficial for recursion within the function body.
let factorial = function fact(n) {
if (n <= 1) {
return 1;
}
return n * fact(n - 1);
};
console.log(factorial(5)); // 120
21. Static Methods
Static methods are functions that belong to a class rather than an instance of the class. They are defined using the static
keyword.
class MathUtils {
static add(a, b) {
return a + b;
}
}
console.log(MathUtils.add(5, 3)); // 8