Function Declaration
- Defined using the
function
keyword.
- Can be called before they are declared (hoisting).
- Suitable for all types of functions.
function myFunction() {
// code
}
Function Expressions
- Assigned to a variable or property.
- Not hoisted; must be defined before use.
- Offers more flexibility than function declarations.
const myFunction = function() {
// code
};
Arrow Functions (introduced in ECMAScript 6)
- Introduced in ECMAScript 6.
- Shorter syntax using the
=>
arrow.
- Lexical scoping of this, making it useful in callbacks.
const myFunction = () => {
// code
};
Anonymous Functions
- Functions without a name.
- Often used as arguments to other functions.
- Can be immediately invoked.
These are functions without a name and are often used as arguments to other functions or for immediate invocation.
const result = (function() {
// code
return something;
})();
Named Function Expressions
- Similar to function expressions but with a name.
- Useful for self-reference or stack traces.
- Similar to function expressions but with a name, which can be useful for self-reference.
const myFunction = function namedFunction() {
// code
};
IIFE (Immediately Invoked Function Expression)
A function that is defined and invoked immediately.
- Defined and executed immediately after creation.
- Isolated scope for preventing variable conflicts.
(function() {
// code
})();
Generator Functions
Functions that can be paused and resumed using the yield keyword.
- Introduced in ECMAScript 6.
- Can pause and resume execution using
yield
.
- Useful for asynchronous programming.
function* myGenerator() {
// code
yield something;
}
Constructor Functions
- Used with the
new
keyword to create instances of objects.
- Initializes object properties and methods.
function MyClass() {
this.property = value;
}
const myObject = new MyClass();
Callback Functions
Functions passed as arguments to other functions and executed later.
- Passed as arguments to other functions.
- Executed later, often after an asynchronous operation.
function fetchData(callback) {
// code to fetch data
callback(data);
}
Recursive Functions
Functions that call themselves either directly or indirectly.
- Calls itself either directly or indirectly.
- Used for tasks that can be broken down into simpler, similar sub-tasks.
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
}
return n * factorial(n - 1);
}