Defining Functions in JavaScript
Function declarations, function expressions, and default parameters.
2 min read
A function is a reusable block of code that takes input, does something, and optionally returns a value. JavaScript has a few different syntaxes for defining one, and they behave slightly differently.
Function declarations
function greet(name) {
return `Hello, ${name}!`;
}
greet("Ada"); // "Hello, Ada!"Function declarations are hoisted — the entire function is available before its line in the file, so you can call it above where it's defined:
sayHi(); // works fine
function sayHi() {
console.log("Hi!");
}Function expressions
A function can also be assigned to a variable, as an unnamed (anonymous) expression:
const greet = function (name) {
return `Hello, ${name}!`;
};Unlike declarations, function expressions are not hoisted with their value — the variable exists, but calling it before this line throws, since greet isn't assigned yet.
Default parameters
Parameters can specify a fallback value used when the caller omits that argument (passes undefined):
function greet(name = "there") {
return `Hello, ${name}!`;
}
greet(); // "Hello, there!"
greet("Ada"); // "Hello, Ada!"Rest parameters
... collects any number of trailing arguments into a real array, replacing the older, clunkier arguments object:
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
sum(1, 2, 3, 4); // 10Return values
A function without an explicit return returns undefined:
function logMessage(msg) {
console.log(msg);
}
const result = logMessage("hi"); // logs "hi"
console.log(result); // undefinedreturn also exits the function immediately — any code after it in the same block never runs.
Which to use
Function declarations are a good default for named, top-level functions — the hoisting means definition order in the file doesn't matter. Function expressions are useful when a function is a value: passed as a callback, stored in an object, or conditionally assigned. The next lesson covers arrow functions, a more compact expression syntax with one important behavioral difference.