Functions
A function is a named, reusable block of code that performs a task. You define it once and call it as many times as you need, giving it different input each time. Functions are the main building blocks of every JavaScript program: the Fee Tracker has one to calculate a late fee, one to format a receipt line, one to validate a form. In JavaScript, functions are also values, which is what makes callbacks, event handlers and array methods possible.
In One Minute
- Declare a function with
function name(parameters) { ... }and call it withname(arguments). return valuesends a result back to the caller and ends the function. Withoutreturn, the result isundefined.- Parameters are the names in the definition; arguments are the values passed in a call.
- Each call gets its own fresh local variables, and is tracked on the call stack.
- Good functions are small, do one job, and have a name that says what that job is.
Declaring and Calling a Function
Syntax
function functionName(parameter1, parameter2) {
// body
return result;
}
functionName(argument1, argument2); // callExample
function lateFee(daysLate) {
const fee = daysLate * 2;
return fee;
}
console.log(lateFee(5));
console.log(lateFee(12));
const total = 120 + lateFee(8);
console.log(total);10
24
136Explanation: lateFee is defined once. Each call passes a different value for daysLate, runs the body with it, and the return statement sends the result back. A call is an expression, so 120 + lateFee(8) uses its result like any other value.
Return Values
return does two things: it gives the function's result to the caller, and it ends the function immediately. Any code after a return in the same path doesn't run:
function status(balance) {
if (balance <= 0) {
return "Paid";
}
return "Owes $" + balance;
console.log("This line never runs");
}
function logOnly(message) {
console.log("LOG:", message);
}
console.log(status(0));
console.log(status(45));
console.log(logOnly("saved"));Paid
Owes $45
LOG: saved
undefinedExplanation: logOnly prints but has no return, so its call evaluates to undefined, which the outer console.log then prints. A function returns exactly one value; to return several, return an object or array: return { total, count };.
Parameters and Local Variables
Parameters behave like local variables that are filled in by the call. Variables declared inside a function are local: they exist only during that call and can't be seen from outside:
function receiptLine(name, amount) {
const formatted = "$" + amount.toFixed(2);
return `${name}: ${formatted}`;
}
console.log(receiptLine("Navika", 120));
console.log(receiptLine("Srihitha", 85.5));
console.log(typeof formatted);Navika: $120.00
Srihitha: $85.50
undefinedEach call gets a fresh set of local variables, so the two calls can't interfere with each other. Outside the function, formatted doesn't exist. The next lesson covers parameters in depth: default values, extra and missing arguments, and rest parameters.
Functions Are Values
In JavaScript, a function is an object you can store in a variable, put in an array, pass to another function, or return from one. A function name without parentheses refers to the function itself; with parentheses, it calls it:
function double(x) {
return x * 2;
}
console.log(typeof double);
console.log(double);
console.log(double(21));
const fn = double;
console.log(fn(5));
console.log([10, 20, 30].map(double));function
[Function double]
42
10
[20, 40, 60]Explanation: [10, 20, 30].map(double) passes the function itself (no parentheses) to map, which calls it once for each item. A function passed to another function to be called later is a callback. This idea runs through the rest of the course: event listeners, timers, array methods and promises all take callbacks.
Hoisting of Function Declarations
A function declaration (a statement starting with function name) is available in its whole scope, even on lines before it is written:
console.log(greet("Advitha"));
function greet(name) {
return `Hello, ${name}!`;
}Hello, Advitha!The engine registers declarations before running the code. This lets you put the main logic at the top of a file and helper functions below. Function expressions (next lessons) don't work this way; the hoisting lesson explains the details.
In Practice
The Fee Tracker's billing logic, split into small functions with one job each. The top-level function reads like a summary of the steps:
const RATE_PER_DAY = 2;
const LATE_FEE_CAP = 30;
const GRACE_DAYS = 10;
function lateFee(daysLate) {
if (daysLate <= GRACE_DAYS) return 0;
return Math.min((daysLate - GRACE_DAYS) * RATE_PER_DAY, LATE_FEE_CAP);
}
function formatUsd(amount) {
return "$" + amount.toFixed(2);
}
function billLine(student) {
const fee = lateFee(student.daysLate);
const total = student.balance + fee;
return `${student.name}: ${formatUsd(total)} (late fee ${formatUsd(fee)})`;
}
console.log(billLine({ name: "Navika", balance: 120, daysLate: 3 }));
console.log(billLine({ name: "Srihitha", balance: 85, daysLate: 16 }));
console.log(billLine({ name: "Advitha", balance: 45, daysLate: 40 }));Navika: $120.00 (late fee $0.00)
Srihitha: $97.00 (late fee $12.00)
Advitha: $75.00 (late fee $30.00)Common Mistakes
Forgetting return. The function computes a value and throws it away; the call gives undefined.
Forgetting the parentheses. console.log(lateFee) prints the function itself. Call it with lateFee(5).
Calling a function when you mean to pass it. button.addEventListener("click", save()) runs save immediately and passes its result. Pass the function: addEventListener("click", save).
Code after return. It never runs. Linters warn about "unreachable code".
Under the Hood
When a function is called, the engine creates an execution context for that call: a record holding its parameters, local variables, and where to return to. Contexts are kept on the call stack, a last-in, first-out list. Calling a function pushes a context; returning pops it, and execution continues in the caller.
function formatUsd(amount) {
console.log(" formatUsd: top of the stack");
return "$" + amount.toFixed(2);
}
function billLine(name, amount) {
console.log(" billLine: calling formatUsd");
const text = formatUsd(amount);
console.log(" billLine: formatUsd returned");
return `${name}: ${text}`;
}
console.log("main: calling billLine");
console.log(billLine("Advitha", 45));main: calling billLine
billLine: calling formatUsd
formatUsd: top of the stack
billLine: formatUsd returned
Advitha: $45.00The stack grows from the main script to billLine to formatUsd, then shrinks back. When an error is thrown, the stack trace you see in the console is a snapshot of this stack: the innermost call on the first line. The stack also has a size limit, which is why a function that calls itself forever fails with RangeError: Maximum call stack size exceeded (see the recursion lesson). And because JavaScript has one call stack on the main thread, a long-running call blocks everything until it returns.
Interview Corner
What does a function return if it has no return statement?
undefined. The same is true for a bare return;. A constructor called with new is the exception: it returns the new object unless it explicitly returns another object.
What is the call stack?
The engine's stack of execution contexts. Each function call pushes a frame with its arguments, local variables and return address; returning pops it. Stack traces show this stack, deep recursion overflows it, and because the main thread has a single stack, long synchronous calls block the event loop.
What does it mean that functions are first-class in JavaScript?
Functions are values (objects). They can be assigned to variables, stored in data structures, passed as arguments (callbacks) and returned from other functions (higher-order functions, closures). They can even have properties.
Practice
Challenge: Write discount(amount, siblings) that returns 10% off for one sibling, 15% off for two or more, and nothing off otherwise. Then write finalPrice(amount, siblings) that uses it and returns the price rounded to cents.
Show solution
function discount(amount, siblings) {
if (siblings >= 2) return amount * 0.15;
if (siblings === 1) return amount * 0.1;
return 0;
}
function finalPrice(amount, siblings) {
return Math.round((amount - discount(amount, siblings)) * 100) / 100;
}
console.log(finalPrice(450, 0));
console.log(finalPrice(450, 1));
console.log(finalPrice(450, 3));450
405
382.5Key Takeaways
| Concept | Example |
|---|---|
| Declaration | function lateFee(days) { ... } |
| Call | lateFee(12) |
| Return several values | return { total, count }; |
| Pass a function | arr.map(double) |
Was this tutorial helpful?