A function declaration is the standard way to define named functions in JavaScript. These functions are hoisted, meaning they can be called before they are defined in the code.
function keyword followed by the function name.console.log(sum(2, 3)); // Output: 5 (hoisting works)
function sum(a, b) {
return a + b;
}
A function expression involves assigning a function to a variable. Unlike declarations, these functions are not hoisted, so you must define them before using them.
const greet = function(name) {
return `Hello, ${name}`;
};
console.log(greet("Alice")); // Hello, Alice
Introduced in ES6, arrow functions provide a shorter syntax and lexical scoping for this. Arrow functions are especially useful for callbacks and inline functions.
(param1, param2) => expressionthis, arguments, super, or new.target.const add = (a, b) => a + b;
console.log(add(2, 3)); // 5
Functions without a name are called anonymous functions. They are commonly used for inline callbacks or temporary usage. It can be made using arrow functions or function expressions.
const numbers = [1, 2, 3];
numbers.forEach(function(num) {
console.log(num * 2);
});
An IIFE is a function that is executed immediately after it is defined. They are useful for creating private scopes to avoid polluting the global namespace.