What is a function for?
A function is a named piece of code you can run whenever you need it. You write the steps once, give them a name, and call that name from anywhere. Without functions you copy the same lines into several places, and then fix the same bug several times.
Declare one with the function keyword, a name, round brackets and a body in braces. Nothing runs at that point; you have only described the work. Calling the function, by writing its name followed by brackets, runs the body.
Function declarations are hoisted: JavaScript knows about them before it runs the file, so you can call one on a line above the place where it is written. Arrow functions stored in const are not, which is one practical difference you will run into.
function welcome() {
console.log("Welcome to Spokes bike shop");
}
welcome();
welcome();

return sends one value back to the place that called it.What is the difference between parameters and arguments?
Parameters are the names in the brackets of the declaration: function rentalCost(hours, helmet). They act like variables that exist only inside the function. Arguments are the actual values you pass when calling it: rentalCost(3, true).
Arguments fill parameters by position. The first argument goes into the first parameter, the second into the second. Names do not matter across the boundary, so calling rentalCost(true, 3) puts true into hours and the result is nonsense without any error.
Pass too few arguments and the missing parameters are undefined. Pass too many and the extra ones are ignored. Neither causes an error, which is why it pays to check the result. When a function needs many values, pass one object instead, as in book({ hours: 3, helmet: true }), so the order stops mattering.
function rentalCost(hours, helmet) {
const base = hours * 6;
return helmet ? base + 2 : base;
}
console.log(rentalCost(3, true));
console.log(rentalCost(3));What does return do, and what if you leave it out?
return ends the function and sends a value back to the caller. The call expression is then replaced by that value, so const cost = rentalCost(3, true); stores 20. The diagram shows this: inputs go in, one value comes out.
A function with no return, or with return; on its own, gives back undefined. That is the cause of the blank price in the demo. The function did the calculation and then threw the result away.
Anything after a return that runs does not run. Use that on purpose for early returns, which handle odd cases at the top of the function. Watch out for one trap: if you put a line break straight after the word return, JavaScript inserts a semicolon there and returns undefined. Keep the value on the same line, or open a bracket on that line.
A function can only return one value. To give back several, return an object or an array: return { total, count };.
function formatPrice(amount) {
return `$${amount.toFixed(2)}`;
}
function noReturn(amount) {
`$${amount.toFixed(2)}`;
}
console.log(formatPrice(4));
console.log(noReturn(4));How do arrow functions work?
An arrow function is a shorter way to write a function, usually stored in a const: const double = (n) => n * 2;. The parameters go in brackets, then =>, then the body.
If the body is a single expression without braces, its value is returned automatically. With braces, you are back to a normal body and must write return yourself. Adding braces to a one-line arrow and forgetting the return is a very common way to get undefined.
To return an object from a one-line arrow, wrap it in round brackets: () => ({ size: "large" }). Without them the braces are read as a function body.
Arrows are the usual choice for short functions passed to other functions, such as event listeners and array methods. Arrow functions also handle this differently from function, which makes a difference once you reach classes and event handlers; for now, either form works for ordinary functions.
const double = (n) => n * 2;
const addTax = (price) => {
const tax = price * 0.2;
return price + tax;
};
console.log(double(4), addTax(10));How do default parameters help?
A default gives a parameter a value when the caller leaves it out: function rentalCost(hours, helmet = false). The default is used when the argument is missing or is undefined. It is not used for null, 0 or an empty string, because those are real values the caller chose to pass.
Defaults replace older patterns such as helmet = helmet || false; at the top of the function. That older form also replaced 0 and empty text, which caused bugs whenever 0 was a sensible value.
Put parameters with defaults after the ones without. A default in the middle forces callers to pass undefined to skip it.
function greet(name, greeting = "Hello") {
return `${greeting}, ${name}.`;
}
console.log(greet("Mo"));
console.log(greet("Mo", "Good morning"));Why can you pass a function to another function?
In JavaScript a function is a value, like a number or a string. You can store it in a variable, put it in an array, and pass it as an argument. A function passed this way is often called a callback, because the other function calls it back later.
You have already seen this with addEventListener("click", handleClick). Note there are no brackets after handleClick. You are handing over the function itself, to be run when the click happens. Writing handleClick() would run it straight away and pass its return value, usually undefined, which is a frequent bug.
The same idea powers array methods: prices.filter(isCheap) runs isCheap once for every price. The Events lens shows which function responded to each click, which is a good way to confirm you passed the right one.
const isCheap = (price) => price < 5;
const applyToAll = (list, action) => {
const result = [];
for (const item of list) {
result.push(action(item));
}
return result;
};
console.log(applyToAll([3, 8, 4], isCheap));How should you name functions?
Name a function after what it does, starting with a verb: formatPrice, addItem, showError, countErrands. A reader should be able to guess the effect from the call alone. Names like data, handle or doStuff force them to read the body.
Functions that answer a yes or no question usually start with is, has or can: isOpen, hasStock. They return a boolean and read well inside an if. Functions that compute and return a value often start with get, calc or format. Functions that change the page often start with show, render or update.
If a name needs and in it, such as validateAndSaveAndShow, the function is doing too much. Split it.
Why keep calculations apart from page changes?
Some functions only compute: they take arguments, return a value, and touch nothing else. These are called pure functions. Given the same input they always return the same output, so they are easy to test in the Console and easy to reuse.
Other functions change the outside world: they update the page, write to storage or send a request. Those effects are what the user sees, so they are necessary. They are also harder to check, because the result lives somewhere else.
Keep the two apart. Let rentalCost do the maths and return a number. Let showCost call it and put the result on the page. When the price is wrong you test rentalCost(3) directly; when the layout is wrong you look at showCost. AI-generated code often mixes them, with one long function that reads inputs, calculates, builds HTML and logs. Pulling out the calculation into its own small function is usually the first improvement worth making.
Use the Step lens to watch a call: the arrow jumps into the function, the parameters appear with their argument values, and when return runs the arrow jumps back to the line that called it.
const rentalCost = (hours, helmet = false) => hours * 6 + (helmet ? 2 : 0);
function showCost(hours) {
const cost = rentalCost(hours);
console.log(`${hours} hours: $${cost}`);
}
showCost(3);Field notes
- A function is a named set of steps you write once and call when needed.
- Parameters are the names in the declaration, and arguments are the values you pass.
- Without
return, a function call gives backundefined. - Arrow functions are a shorter way to write a function, often stored in a
const.
Easy to get wrong
Without return the function gives back undefined, however much work it did.
Braces turn the arrow's body into a block, which needs an explicit return. Drop the braces for a one-expression arrow.
A function name on its own only refers to the function. The brackets are what call it.
A line break right after return ends the statement, so the function returns undefined and the next line never runs.
Questions people ask
Should I use function declarations or arrow functions?
Both are fine for ordinary functions. Many teams use declarations for named, top-level functions and arrows for short callbacks. Pick a habit and stay consistent within a file.
Can a function change a variable outside it?
Yes, if the variable is declared with let in an outer scope. It works, but it makes the function harder to reason about. Prefer returning a new value and letting the caller store it.
How many parameters is too many?
Past three, callers start mixing up the order. Pass a single object with named properties instead, and destructure it in the parameter list.
Why do I see undefined in the Console after calling a function there?
The Console shows the return value of whatever you typed. A function that only logs and does not return gives undefined, so you see the log line and then undefined.
What is a method?
A method is a function stored as a property of an object, such as name.trim() or list.push(). It is called with a dot. You will write your own in the objects lesson.