Functions are the building blocks of JavaScript programs. They let you write a piece of code once and use it many times, with different inputs producing different outputs. Think of them as recipes: you write down the instructions once, then follow them whenever you need to cook that dish.
Function declarations
The most straightforward way to create a function is with a function declaration:
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // "Hello, Alice!"
console.log(greet("Bob")); // "Hello, Bob!"Let's break down the syntax:
function, the keyword that tells JavaScript you're defining a functiongreet, the name you'll use to call this function(name), the parameter, a placeholder for the input value{ ... }, the function body, where the work happensreturn, sends the result back to wherever called the function
HoistingWhat is hoisting?JavaScript's behavior of moving function and variable declarations to the top of their scope during compilation, so they can be referenced before they appear in the code.: declarations float to the top
Function declarations have a special property called hoisting. JavaScript moves them to the top of their scopeWhat is scope?The area of your code where a variable is accessible; variables declared inside a function or block are invisible outside it. during compilation, which means you can call them before they appear in your code:
// This works, even though greet() is called before it's defined
console.log(greet("World")); // "Hello, World!"
function greet(name) {
return `Hello, ${name}!`;
}TypeError that looks confusing. Pick one style per context (declarations for top-level utilities, arrows for callbacks) and stick with it.Function expressions
Another way to create functions is by assigning them to variables:
const add = function(a, b) {
return a + b;
};
console.log(add(2, 3)); // 5Notice the semicolon at the end? That's because this is a variable assignment statement. The function on the right side is called an anonymous functionWhat is anonymous function?A function with no name, typically assigned to a variable or passed as an argument - used frequently with arrow functions and callbacks.: it has no name, though JavaScript gives it an internal name for debugging purposes.
Named function expressions
You can give your function a name even in an expression:
const factorial = function calc(n) {
if (n <= 1) return 1;
return n * calc(n - 1); // The name 'calc' is available inside
};
// Outside the function, you must use 'factorial'
console.log(factorial(5)); // 120
// console.log(calc(5)); // ReferenceError: calc is not definedThe name calc is only available inside the function itself, useful for recursionWhat is recursion?When a function calls itself - requires a base case to stop, otherwise it causes a "maximum call stack size exceeded" error. when the outer variable might change.
No hoistingWhat is hoisting?JavaScript's behavior of moving function and variable declarations to the top of their scope during compilation, so they can be referenced before they appear in the code. for expressions
Unlike declarations, function expressions are NOT hoisted:
// This throws an error!
console.log(multiply(2, 3)); // TypeError: multiply is not a function
const multiply = function(a, b) {
return a * b;
};The variable multiply IS hoisted, but as undefined. The function assignment happens at runtimeWhat is runtime?The environment that runs your code after it's written. Some languages need a runtime installed on the machine; others (like Go) bake it into the binary. when the code reaches that line.
Parameters vs arguments
These terms are often confused, but they mean different things:
| Term | Definition | Example |
|---|---|---|
| Parameter | Variable in the function definition | function greet(name), name is a parameter |
| Argument | Actual value passed when calling | greet("Alice"), "Alice" is an argument |
// Parameters: width, height
function calculateArea(width, height) {
return width * height;
}
// Arguments: 10, 20
const area = calculateArea(10, 20); // 200Default parameters
You can provide default values for when an argument isn't passed:
function greet(name = "Guest") {
return `Hello, ${name}!`;
}
greet(); // "Hello, Guest!"
greet("Alice"); // "Hello, Alice!"Default parameters can even reference other parameters:
function greet(greeting, name = greeting + " friend") {
return `${greeting}, ${name}!`;
}
greet("Hello"); // "Hello, Hello friend!"
greet("Hi", "Alice"); // "Hi, Alice!"RestWhat is rest?An architectural style for web APIs where URLs represent resources (nouns) and HTTP methods (GET, POST, PUT, DELETE) represent actions on those resources. parameters
When you don't know how many arguments you'll receive, use rest syntax:
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3); // 6
sum(1, 2, 3, 4); // 10
sum(); // 0The ...numbers collects all remaining arguments into a real array. This is different from the old arguments object, which had array-like behavior but wasn't a true array.
... syntax but in opposite contexts. Rest collects multiple items into an array (in function parameters). Spread expands an array into individual items (in function calls or array literals).Return values
Functions can send data back using the return statement:
function double(x) {
return x * 2;
}
const result = double(5); // 10Important: A function stops executing as soon as it hits a return. Any code after return won't run:
function example() {
return "I'm done!";
console.log("This never runs"); // Unreachable code
}Functions without return
If you don't use return, the function returns undefined:
function logMessage(msg) {
console.log(msg);
// No return statement
}
const result = logMessage("Hello"); // Logs "Hello"
console.log(result); // undefinedThis is fine for functions that perform actions (like logging) rather than calculating values.
Quick reference
| Feature | Declaration | Expression | Arrow |
|---|---|---|---|
| Syntax | function name() {} | const name = function() {} | const name = () => {} |
| Hoisted? | Yes | No | No |
Has own this? | Yes | Yes | No (inherits) |
| Best for | Top-level utilities | When order matters | Callbacks, short functions |
// Function declaration
function greet(name) {
return `Hello, ${name}!`;
}
// Function expression
const add = function(a, b) {
return a + b;
};
console.log(greet("Alice")); // "Hello, Alice!"
console.log(add(2, 3)); // 5
// Default parameters
function power(base, exponent = 2) {
return base ** exponent;
}
console.log(power(3)); // 9 (3²)
console.log(power(2, 3)); // 8 (2³)
// Rest parameters
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15