JavaScript Functions
Published by Brayan K
Learn how to create reusable, organized, and efficient blocks of code with functions — one of the most powerful features in JavaScript.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Give a calculation a callable name
Suppose two order lines need the same calculation: quantity multiplied by unit price. Repeating the arithmetic at every call site makes it easy to change one copy and forget another. A function gives that calculation one definition and lets each caller supply its own values.
function lineTotal(quantity, unitPrice) {
return quantity * unitPrice;
}
const notebooks = lineTotal(3, 4);
const pens = lineTotal(5, 2);
console.log(notebooks);
console.log(pens);
console.log(notebooks + pens);
// ✅ Expected output:
// 12
// 10
// 22The names quantity and unitPrice are parameters: local names the body uses. In lineTotal(3, 4), the values supplied by the caller are arguments. Position matters: the first argument becomes the first parameter. The call evaluates to the value supplied by return, so another expression can use it.
Trace a call before compressing it into one line. First identify the argument values, then substitute them into the body mentally, then follow the returned value back to the caller. The function does not have to print in order to be useful.
A definition waits for a call
function announce() {
console.log("Packing now");
}
console.log("Definition reached");
announce();
console.log("Call finished");
// ✅ Expected output:
// Definition reached
// Packing now
// Call finishedReaching the declaration makes the function available; it does not execute the statements in its body. The parentheses in announce() perform the call. Without parentheses, the name refers to the function itself, which is useful when you want to pass an action somewhere else.
function double(quantity) {
return quantity * 2;
}
console.log(typeof double);
console.log(typeof double(3));
console.log(double(3));
// ✅ Expected output:
// function
// number
// 6Do not add parentheses automatically to every function name you see. An event handler often needs the function value so the browser can call it later. Events owns that event-driven use.
A message on screen is not a return value
function lineTotal(quantity, unitPrice) {
console.log(quantity * unitPrice);
}
const total = lineTotal(3, 4);
console.log(total);
// ✅ Expected output:
// 12
// undefinedThe calculation was printed, which can make this bug look like success. But the function reached its end without returning a value. The caller receives undefined; assigning that result does not capture whatever happened to be logged.
function lineTotal(quantity, unitPrice) {
return quantity * unitPrice;
}
const total = lineTotal(3, 4);
console.log(total);
console.log(total + 2);
// ✅ Expected output:
// 12
// 14Returning keeps calculation separate from presentation. One caller can log the result; another can add a packing fee. Writing return console.log(...) does not solve the problem, because console.log itself returns undefined. Return the value you want the caller to receive.
A result is not necessarily callable. Here, the function call produces a number. Adding another pair of parentheses tries to call that number as a function and raises a TypeError.
function lineTotal(quantity, unitPrice) {
return quantity * unitPrice;
}
const total = lineTotal(3, 4);
total();
// ✅ Expected error:
// TypeError: total is not a functionMake an omitted argument a deliberate case
function lineTotal(quantity, unitPrice) {
return quantity * unitPrice;
}
console.log(lineTotal(3));
// ✅ Expected output:
// NaNThe missing parameter receives undefined. This arithmetic produces NaN, so “no exception” does not mean “correct answer.” Decide whether an omitted input should be rejected by your application or has a meaningful default. Do not invent a default merely to hide a caller bug.
function displayName(name = "Guest") {
return name;
}
console.log(displayName());
console.log(displayName(undefined));
console.log(displayName(null));
console.log(JSON.stringify(displayName("")));
// ✅ Expected output:
// Guest
// Guest
// null
// ""A default is used for an omitted argument or an explicit undefined. It is not used for null or an empty string. In the last line, JSON.stringify makes the empty returned text visible as a quoted string. Input validation is a separate decision from choosing a default.
Keep the returned expression with return
function packingFee() {
return
2 + 1;
}
console.log(packingFee());
// ✅ Expected output:
// undefinedJavaScript inserts a statement boundary after this return. The function exits without a value before reaching the expression underneath. Indentation does not override that rule. Put the expression on the return line, or open its parentheses there when it needs several lines.
function packingFee() {
return (
2 + 1
);
}
console.log(packingFee());
// ✅ Expected output:
// 3Once return executes, the remaining ordinary statements in that function body do not run. It returns from this call; it does not end the caller’s whole program. Cleanup behavior involving try/finally belongs to error handling.
Arrow braces change what must be written
const doubleExpression = quantity => quantity * 2;
const doubleBlock = quantity => { return quantity * 2; };
const missingReturn = quantity => { quantity * 2; };
console.log(doubleExpression(4));
console.log(doubleBlock(4));
console.log(missingReturn(4));
// ✅ Expected output:
// 8
// 8
// undefinedAn expression-bodied arrow returns its expression. Once you use a block body with braces, you need an explicit return when the caller should receive a value. The number of physical lines is not the rule: a one-line block can still forget its return.
A function expression can also be assigned to a name, such as const double = function (quantity) { return quantity * 2; }. Declarations, expressions and arrows have differences beyond appearance. Hoisting owns initialization timing, and ES6+ Features places arrows among the language features. Do not assume an arrow can replace every use of a regular function.
Keep local work local
function lineTotal(quantity, unitPrice) {
const subtotal = quantity * unitPrice;
return subtotal;
}
console.log(lineTotal(2, 6));
console.log(subtotal);
// ✅ Expected output:
// 12
// ✅ Expected error:
// ReferenceError: subtotal is not definedReturn the local result and bind it to a name in the caller if the caller needs to keep it. Reading the internal name from outside is not an alternative to return. Scope & var/let/const (TDZ) owns visibility rules, while Closures and Scope explains retained outer bindings.
Complete a reusable packing calculation
The function adds a fixed packing fee to a line cost. Fill the returned expression and the function call, then check that the caller can print the result.
function packedTotal(quantity, unitPrice) {
return ___; // 👉 replace ___ with quantity * unitPrice + 2
}
const total = ___; // 👉 replace ___ with packedTotal(3, 5)
console.log(total);
// ✅ Expected output:
// 17Build a subtotal from two calls
Write lineTotal(quantity, unitPrice) so it returns a number and does not log. Use it for three notebooks at four units each and five pens at two units each. Add the two returned numbers, then print only the combined subtotal. Changing the pen quantity should require changing a call, not the function body.
function lineTotal(quantity, unitPrice) {
return quantity * unitPrice;
}
const subtotal = lineTotal(3, 4) + lineTotal(5, 2);
console.log(subtotal);
// ✅ Expected output:
// 22If the result is NaN, inspect the value returned by each call before changing the addition. If intermediate totals print but the combined result fails, look for a function that logs instead of returning. This narrows the failure to the input/result contract.
References: MDN’s functions guide, return and default parameters.
Practice quiz
What does this complete program print? function announce() { console.log("Inside"); } console.log("Outside");
- Outside
- Inside Outside
- Inside
- Nothing is printed
Answer: Outside. The function is defined but never called.
What does this complete program print? function cost(quantity, price) { return quantity * price; } console.log(cost(4, 3));
- 43
- 12
- 7
- undefined
Answer: 12. Arguments bind by position, and return sends the multiplication result to console.log.
What does this complete program print? function double(value) { console.log(value * 2); } console.log(double(3));
- 6
- undefined
- 6 undefined
- 6 6
Answer: 6 undefined. The inner log prints the calculation; the outer log prints the undefined return value.
What does this complete program print? function label(value = "Guest") { return value; } console.log(label(null));
- Guest
- undefined
- TypeError
- null
Answer: null. An explicit null does not activate a default parameter.
What does this complete program print? const double = value => { value * 2; }; console.log(double(4));
- undefined
- 8
- 4
- SyntaxError
Answer: undefined. A block body without return finishes with undefined.
What does this complete program print? function fee() { return 3; } console.log(fee());
- 3
- undefined
- 0
- SyntaxError
Answer: undefined. A line terminator immediately after return ends that statement.
What does this complete program print? function addFee(value) { return value + 2; } console.log(addFee(addFee(3)));
- 5
- 3
- 7
- undefined
Answer: 7. The inner call returns first; its value becomes the outer call’s argument.
Which error ends this program? function makeTotal() { const total = 7; return total; } console.log(total);
- 7
- undefined
- TypeError: total is not a function
- ReferenceError: total is not defined
Answer: ReferenceError: total is not defined. The total binding exists inside makeTotal, not in the caller.
Continue this course
- Previous: Variables and Data Types
- Next: Strings & String Methods — slice, split, replace, template literals and the string methods you'll use daily
- Quick reference: JavaScript cheat sheet › Functions