Explain it simply
Explain it simply
Think of a recipe card. It has a title such as "fried egg" (the name), a list of ingredients (the parameters), the steps, and the dish you end up with (the return value). You write the card once and reuse it every time you cook, with however many eggs you have that day.
A JavaScript function is that recipe card. Writing function add(a, b) { return a + b; } runs nothing yet; only calling add(5, 7) runs the code inside and hands back 12. That lets you call one name from many places instead of pasting the same code everywhere.
Problem → Why → Solution
The problem: one missing return turns a total into NaN
This function applies a discount. Tested with 10 percent, it works. But for an order with no discount (percent = 0), the checkout page shows the total as NaN. No error message appears, so it is hard to tell where the bug comes from.
function applyDiscount(price, percent) {
if (percent > 0) {
return price - (price * percent) / 100;
}
// no return on this path
}
const total = applyDiscount(50, 0) + 5; // shipping
console.log(total); // NaNWhy NaN?
When a function reaches its end without hitting a return statement, JavaScript returns undefined automatically. With percent at 0 the if is skipped, undefined comes back, and undefined + 5 is NaN. A function that returns a number on some paths and undefined on others gives its callers an unclear promise. Every path should return the same kind of value.
Core concept: declare, call, return
Without functions, the code that prices an item would be pasted everywhere it is needed. On the day the tax rate changes, fixing four of the five copies leaves one page showing wrong prices. A function keeps the logic in one place and lets everything else call it by name, which removes that whole class of bug.
function name(param1, param2) { ... } is a function declaration. The names in the parentheses are parameters, local variables that exist only inside the function. When you call name(5, 7), the values you pass are arguments, and they fill the parameters in order: a becomes 5 and b becomes 7. Variables declared with let or const inside the function are invisible from outside.
return hands a value back to the caller and ends the function immediately; code below the return does not run. With no return, or a bare return;, the result is undefined. console.log() only shows something on screen and does not send a value back, so calculation functions should return their result and let the caller decide whether to print it.
JavaScript does not check the number of arguments. Pass too few and the missing parameters are undefined; pass too many and the extras are ignored. With a default parameter such as function greet(name = "friend"), the default is used whenever the argument is missing or undefined.
Function declarations are hoisted, so you can call them from higher up in the file than where they are written. A function expression such as const square = function (n) { ... } is stored in a variable, so calling it before that line runs throws a ReferenceError. Finally, a function whose output depends only on its input and which changes nothing outside itself is called a pure function, and it is the easiest kind to test.
- Caller passes arguments
- They fill parameters in order
- The body runs
- return hands back a value and stops
If no return is reached, the caller receives undefined.
General pattern
function functionName(paramA, paramB = defaultValue) {
// work with paramA and paramB
return result;
}
const result = functionName(argA, argB);
const otherName = function (param) {
return result;
};A declaration has a name, a parameter list and a body, and return hands back the result. Calling it puts arguments inside the parentheses. The last shape is a function expression stored in a variable.
Example: a function that adds two numbers
This is about the simplest useful function: it takes two numbers and returns their sum. Notice that defining the function and calling it are two separate steps.
// Function definition
function add(a, b) {
return a + b;
}
// Calling the function
let sum = add(5, 7);
console.log("The sum is: " + sum);Code breakdown
- Line 2
function add(a, b) {Declares a function named add. a and b are parameters with no values until the function is called; this line on its own runs nothing.
- Line 3
return a + b;Computes a + b, sends the result back to the caller and ends the function. Writing only console.log(a + b) here would leave sum as undefined.
- Line 7
let sum = add(5, 7);Calls add with the arguments 5 and 7, so a = 5 and b = 7, and stores the returned 12 in sum.
- Line 8
console.log("The sum is: " + sum);The caller does the printing, outside the function, so add stays reusable in places that do not want output, such as another calculation.
The sum is: 12Missing and extra arguments, defaults and hoisting
This snippet gathers the rules from the concept section so you can run them. In addLoose(5), b is undefined and 5 + undefined is NaN. square is called above its declaration and still works, because declarations are hoisted.
function greet(name = "friend") {
return "Hello, " + name + "!";
}
console.log(greet("Mya")); // Hello, Mya!
console.log(greet()); // Hello, friend!
function addLoose(a, b) {
return a + b;
}
console.log(addLoose(5)); // NaN: b is undefined
console.log(addLoose(5, 7, 100)); // 12: the extra argument is ignored
console.log(square(4)); // 16: declarations are hoisted
function square(n) {
return n * n;
}
const cube = function (n) {
return n * n * n;
};
console.log(cube(2)); // 8: only works after this const line has runPure functions and side effects
addToTotal changes the outer runningTotal variable, so its result changes with every call: passing the same argument 10 twice gives 10 and then 20. sum is pure, because its result comes only from its input, so every call with the same numbers agrees. When side effects such as printing or writing files are unavoidable, compute with pure functions and keep the side effects at the edges of the program.
let runningTotal = 0;
function addToTotal(amount) { // impure: changes outside state
runningTotal += amount;
return runningTotal;
}
function sum(a, b) { // pure: depends only on its input
return a + b;
}
console.log(addToTotal(10), addToTotal(10)); // 10 20
console.log(sum(10, 10), sum(10, 10)); // 20 20In real projects
Where functions show up in real projects
A shopping cart computes each line's price with a pure function such as calculateLineTotal(price, quantity, discount). The cart page, the checkout page, the email receipt and the admin report all call that one function, so a change to the discount rules is made in a single place. Because it is pure, unit tests can cover normal input, a quantity of 0, a negative price and a "10" arriving as a string without ever opening a browser.
In large codebases, function names act as documentation: reading formatDate, isValidEmail or sendWelcomeEmail tells you what happens without reading the body. Splitting work so each function does one job makes bugs easier to locate, code easier to reuse and tests easier to write.
Common mistakes
Common mistakes
1. Using console.log instead of return
function total(a, b) { console.log(a + b); } shows the right number on screen, but after const t = total(2, 3); t is undefined. If the result is used again later, return it.
2. Forgetting the parentheses
console.log(add) does not run the function; it prints the function itself ([Function: add] in Node). "Total: " + getTotal pastes the function's whole source code into the string. Calling it needs parentheses: add(5, 7).
3. Adding strings that came from input
When a form gives you "5" and "7" and you call add("5", "7"), + joins text and you get "57" instead of 12. Convert with Number() inside the function or before the call, and check for NaN.
Best practices
Best practices
- Name functions with a verb that says what they do, such as calculateTotal or isAdult.
- Let each function do one job; a name containing "and", such as validateAndSave, is a sign to split it.
- Return the same kind of result on every path, and choose null or an error for invalid input on purpose.
Mini challenge
Mini challenge: a pure line-total function
Write lineTotal(), which prices one shopping-cart line, and formatMoney(), which formats the amount, then test them with normal, zero and invalid input.
- lineTotal(price, quantity, discountPercent) with discountPercent defaulting to 0
- Return null when price or quantity is not a number or is negative
- Return the result rounded to 2 decimals; do not print inside lineTotal
- formatMoney(amount) returns "invalid input" for null and a string like "$30.00" otherwise
function lineTotal(/* TODO: price, quantity, discountPercent with a default */) {
// TODO: return null for non-number or negative price/quantity
// TODO: apply the discount and round to 2 decimals
}
function formatMoney(amount) {
// TODO: "invalid input" for null, otherwise "$" + 2 decimals
}
// TODO: print formatMoney(lineTotal(...)) for:
// (10, 3), (19.99, 2, 10), (5, 0), (-5, 2), ("10", 3)Expected: $30.00 $35.98 $0.00 invalid input invalid input
Show hint
Check types with typeof price !== "number". Round with Math.round(x * 100) / 100 and format with amount.toFixed(2).
Show solution
function lineTotal(price, quantity, discountPercent = 0) {
if (typeof price !== "number" || typeof quantity !== "number") return null;
if (price < 0 || quantity < 0) return null;
const gross = price * quantity;
const net = gross - (gross * discountPercent) / 100;
return Math.round(net * 100) / 100;
}
function formatMoney(amount) {
if (amount === null) return "invalid input";
return "$" + amount.toFixed(2);
}
console.log(formatMoney(lineTotal(10, 3)));
console.log(formatMoney(lineTotal(19.99, 2, 10)));
console.log(formatMoney(lineTotal(5, 0)));
console.log(formatMoney(lineTotal(-5, 2)));
console.log(formatMoney(lineTotal("10", 3)));Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Declaring a function runs nothing; calling name(arguments) runs it.
- return hands back a value and stops the function; reaching the end without one gives undefined.
- Missing arguments become undefined and extras are ignored, so protect parameters with defaults.
- Declarations are hoisted, but function expressions stored in a const are not.
- Pure functions return the same output for the same input, which makes them the easiest to test.
MDN — JavaScript Guide — MDN Web Docs