Function Declaration
A function declaration defines a named function that is hoisted to the top of its scope.
function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Alice")); // Hello, Alice!
console.log(greet("Bob")); // Hello, Bob!
Try it Yourself →
Function declarations are hoisted, meaning you can call them before they appear in the code.
console.log(double(5)); // 10
function double(n) {
return n * 2;
}
Function Expression
A function expression assigns a function to a variable. These are not hoisted.
const multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 3)); // 12
Function expressions are useful when you need to pass a function as an argument or assign it conditionally.
Anonymous Functions
Functions without a name are called anonymous. They are often used as callbacks.
const numbers = [1, 2, 3, 4];
const tripled = numbers.map(function(n) {
return n * 3;
});
console.log(tripled); // [3, 6, 9, 12]
IIFE (Immediately Invoked Function Expression)
An IIFE runs as soon as it is defined, creating a private scope.
(function() {
const secret = "This is private";
console.log(secret);
})();
// secret is not accessible outside