T4 JavaScript · Lesson 3
Functions
Writing a job once and using it everywhere: declaring and calling functions, parameters and default values, return and what it gives back, function expressions and arrow functions, functions passed to other functions, and how calls stack up and show in a trace.
- write a function declaration, and call it as often as you need
- pass values in with parameters, and give a parameter a default value
- give a value back with return, and tell return apart from console.log
- write a function as an expression and as an arrow function, and say where each can be called
- pass a function to another function as a callback
- read a trace of calls, and keep each function to one job
The back cover
Good cooks do not rewrite a recipe each morning. They write it once and follow it whenever it is needed, with a little more sugar for one guest and a little less for another. Programs work best the same way: each job written once, and used everywhere.
These pages show how to declare a function and call it, and how parameters let a call pass values in. They show what return hands back, and how a function can be kept as a value, written short as an arrow and passed to another function as a callback. They end with the call stack, which keeps track of functions calling functions.
Before you start
The story: Seven gates, two fares
The tram depot under the Clock Tower is full of shouting. Last week the fare on the harbour line went up from ₹5 to ₹6. Now the passengers at four gates pay ₹5, the passengers at three gates pay ₹6, and both queues are sure that the other is being cheated.
Master Hakim Verge unrolls the depot's script across his bench. The rule for the fare is written out seven times, once for each gate, in seven slightly different ways. Someone changed three of them and missed the rest.
"A rule written seven times is seven rules," says Master Verge. "Sooner or later they disagree. Every rule should live in one place, and every gate should ask it." Corin starts counting the lines he will have to change.
So far, every program in this track has run once, from the top to the bottom. Real programs do the same jobs again and again: work out a fare for every passenger, check every form, greet every visitor. Writing a job out each time it is needed is slow, and, as the depot found, dangerous. This lesson shows how to write a job once, give it a name, and use it wherever it is needed.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| const and let. | const rate = 18; | A function can be kept in a name too. |
| Template literals. | `Namaste, ${name}` | Many functions build text. |
| undefined. | let seat; holds undefined. | A missing value, and a missing answer. |
| Methods. | "chai".toUpperCase() | A method is a function that belongs to a value. |
| The brackets of a call. | Math.round(2.5) | Every call is a name and brackets. |
| if and else. | if (age < 0) { ... } | A function can decide, and stop early. |
| The ternary. | n === 1 ? "item" : "items" | A short way to give back one of two values. |
| ?? for a default. | name ?? "Guest" | Parameters have their own way to set one. |
| The arrow =>. | marks => 90 is a function. | Now you learn to write them on purpose. |
| Reading a trace. | at line 2 | Traces name each function they pass through. |
| typeof. | typeof (x => x) gives function. | A function is a value like any other. |
By the end of this lesson you will be able to:
- write a function declaration, and call it as often as you need;
- pass values in with parameters, and give a parameter a default value;
- give a value back with
return, and tell return apart fromconsole.log; - write a function as an expression and as an arrow function, and say where each can be called;
- pass a function to another function as a callback;
- read a trace of calls, and keep each function to one job.
How to follow this lesson
Every block on this page runs. When a function gives a surprising answer, print what goes in and what comes out: console.log(fare(3), typeof fare(3));. Most bugs in this lesson are a value that went in wrongly, or an answer that never came back.
In one line
A function is a named job, written once and run whenever it is called, with values going in and an answer coming back.
Writing a job once: declaring and calling
At a glance
A recipe card for masala chai lists its steps once: boil the water, add the tea, the ginger and the milk, then strain. The card does not make tea. It waits until someone says make the chai, and then the steps are followed from the top.
A function declaration, function name() { ... }, stores a job under a name in the same way. Its body runs only when the function is called, with round brackets after its name. Write each rule once as a function, name it with a verb, and call it wherever the job is needed.
Take a guess: Does a function's code run when it is declared, or when it is called?
A recipe card for masala chai lists its steps once: boil the water, add the tea, the ginger and the milk, then strain. The card does not make tea. It waits in the kitchen until someone says "make the chai", and then the steps are followed, from the top. Say it again tomorrow, and they are followed again. Nobody rewrites the recipe each morning.
A function is a recipe card for code. You write its steps once and give them a name. The steps do nothing until the name is called, and they can be called as often as you like.
A named block of code that does one job. Writing it is called declaring or defining the function; running it is called calling it.
function greet() {
console.log("Namaste");
}
greet();
greet();
Namaste
Namaste
Read the declaration part by part. The word function says that a function is being made. greet is its name, chosen by you, with the same rules as any other name. The round brackets will hold the values it needs, and are empty for now. The braces hold the body: the steps of the job.
The last two lines are calls. A call is the function's name followed by round brackets. Each call runs the whole body once, from the top, and then the program carries on from the line after the call. Two calls, so Namaste is printed twice.
A statement that makes a function with a name: function name() { ... }. It is one of several ways to make a function; this section shows the most common one, and later sections show the others.
Nothing happens until the call
Declaring a function only stores the recipe. If you never call it, its body never runs, and nothing is printed:
function greet() {
console.log("Namaste");
}
console.log(typeof greet);
greet;
function
The name greet holds a value of the type function, as typeof shows. The last line names the function but has no brackets, so it is not a call, and the body does not run. The brackets are what say "do it now". A function is a value, and printing one shows what it is, not what it does:
function greet(name) {
return "Hi " + name;
}
console.log(greet);
[Function: greet]
You have been calling functions since the Learning to learn step: console.log("Namaste") calls the function console.log, and Math.round(2.5) calls Math.round. A function that belongs to a value, such as toUpperCase on a string, is called a method. The only new thing here is that you now write functions of your own.
Why write functions at all?
Look back at the tram depot. The fare rule was written out seven times, and when it changed, four copies were missed. Had it been one function, called from seven gates, the change would have been made once, and all seven gates would have agreed. Functions give three things:
- One place for each rule. A change is made once, and every caller gets it.
- A name for each job.
fareFor(passenger)says what a line does, where seven lines of arithmetic would not. - Pieces that can be tested alone. A function can be called with chosen values, and its answer checked, before it is used anywhere.
A useful habit for naming: a function does something, so its name is usually a verb, or starts with one: greet, addGst, printTicket, isAdult. A name that starts with is or has, such as isAdult, is for a function that answers a yes-or-no question.
Calling a function that is not there
A call must use the exact name, capitals included. And only a function can be called; brackets after any other value are an error:
function area(length, width) {
return length * width;
}
console.log(Area(5, 3));
Uncaught ReferenceError: Area is not defined
at line 4
const price = 100;
price();
Uncaught TypeError: price is not a function
at line 2
The first message is the one you met for any misspelt name. The second is new: price exists, but it holds a number, and a number cannot be run. When you see "is not a function", print typeof of the name before the brackets.
Worked example 1
A school's notice board prints the same three-line header before every notice: the school's name, a line of dashes made with "-".repeat(20), and the date. Write the header once as a function, and use it for two notices.
What we have: three lines that repeat before every notice
What we need: the lines written once, and printed before each of two notices
The plan: put the three lines in the body of a function named printHeader, then call it before each notice
function printHeader() {
console.log("Vidya Niketan School");
console.log("-".repeat(20));
console.log("Monday, 9 November");
}
printHeader();
console.log("Sports day is on Friday.");
printHeader();
console.log("The library opens at 8.");
Vidya Niketan School
--------------------
Monday, 9 November
Sports day is on Friday.
Vidya Niketan School
--------------------
Monday, 9 November
The library opens at 8.
- Each call runs the three lines of the body, and then the program carries on with the notice below it.
The header is written once, in printHeader, and printed before both notices.
Check: if the school changes its name, one line in printHeader changes, and every notice after it shows the new name.
A path that fails: copying the three lines before each notice. It prints the same today, but the first time one copy is changed and another is missed, the notices disagree, as the depot's gates did.
When you are stuck: a function does nothing
Check that it is called: a call has brackets, as in greet();. A name on its own runs nothing.
Check that the call comes after the program has read the function, and that the spelling and capitals match.
Put a console.log("inside greet"); as the first line of the body, to see whether the body runs at all.
If you see "is not a function", print typeof of the name: it holds something other than a function.
Your turn
function beep() {
console.log("beep");
}
beep();
console.log("after");
beep();
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
beep
after
beep
- The declaration prints nothing by itself.
- The first call prints beep.
- The program carries on and prints after.
- The second call prints beep again.
It prints beep, after, beep.
A program declares function hello() { console.log("hello"); } and then has the line hello;. What does it print, and why?Tap to reveal
- hello; names the function but has no brackets, so it is not a call.
- The body never runs, so nothing is printed.
It prints nothing; the call needs brackets: hello();.
Write a function named line that prints 10 stars, and call it three times.Tap to reveal
function line() {
console.log("*".repeat(10));
}
line();
line();
line();
**********
**********
**********
The body runs once for each call: three lines of stars.
Did you know?
A word for a job
The word function began as an ordinary word for a job. In August 1673, Leibniz wrote of lines that, in a given figure, perform some function, using the word in its usual sense. In 1748, Euler's Introductio in analysin infinitorum brought the function concept to prominence in mathematics. A JavaScript function keeps both sides: a job to do, and an answer worked out from its inputs.
Why it fits here: It matches this topic's picture: a function is a job written once, which can also hand an answer back.
Sources: MacTutor History of Mathematics: The function concept; Wikipedia: Function (mathematics)
Don't Repeat Yourself
Writing each rule once has a famous name: Don't Repeat Yourself, or DRY. Andy Hunt and Dave Thomas stated it in their book The Pragmatic Programmer: every piece of knowledge must have a single, unambiguous, authoritative representation within a system. They apply it broadly, from code to test plans and even documentation. A function is the everyday tool for it.
Why it fits here: It is the reason this topic writes each rule once as a function: change the rule in one place, and every caller follows.
Sources: The Pragmatic Programmer: tips; Wikipedia: Don't repeat yourself
In one line
A function declaration, function name() { ... }, stores a job under a name, and its body runs only when the function is called with brackets. Write each rule once as a function, name it with a verb, and call it wherever the job is needed.
Values going in: parameters
At a glance
A chai recipe says add the sugar, but how much? One family takes two spoons, another none. A good recipe leaves a gap, and the amount is given each time the chai is made. Functions leave gaps in the same way.
Parameters are the gaps in a function's declaration, and arguments are the values a call puts in them, matched by position. A missing argument is undefined, and an extra one is ignored. A default, as in name = "Guest", fills a gap that is left empty.
Take a guess: If a function has two parameters and you pass one argument, what is the second?
A recipe for chai says "add the sugar", but how much? One family takes two spoons, another takes none. A good recipe leaves a gap: "add as many spoons of sugar as you like". The steps stay the same, and the amount is given each time the chai is made. Functions leave gaps in the same way.
A name in the round brackets of a function's declaration. It is a gap in the recipe: inside the body it holds whatever value the caller gave.
The value given for a parameter in a call. In greet("Asha"), the argument is the string Asha.
function greet(name) {
console.log(`Namaste, ${name}`);
}
greet("Asha");
greet("Ravi");
Namaste, Asha
Namaste, Ravi
In the first call, the argument "Asha" goes into the parameter name, and the body prints Namaste, Asha. In the second, name holds "Ravi". The body is the same; only the value in the gap changes. A way to remember the two words: the parameter is the placeholder in the recipe, and the argument is the actual value on the day.
More than one parameter
A function can have as many parameters as it needs, separated by commas. The arguments are matched to them by position: the first argument goes into the first parameter, the second into the second, and so on.
function area(length, width) {
return length * width;
}
console.log(area(4, 3), area(4), area(4, 3, 99));
12 NaN 12
The word return gives the answer back to the caller; the next section is about it. Look at the three calls. area(4, 3) gives 4 × 3 = 12. area(4) has no second argument, so width holds undefined, and 4 × undefined is NaN. area(4, 3, 99) has one argument too many, and the extra one is quietly ignored.
Neither of those is an error. JavaScript lets a call give fewer or more arguments than the function has parameters. A missing argument is undefined, and an extra one is dropped. So when a function gives NaN or undefined, check that each call gives every argument, in the right order.
A common mistake
Swapping the order of arguments. For area it does not matter, as 4 × 3 is 3 × 4. But for a function such as divide(total, people), divide(4, 1000) gives 0.004 where divide(1000, 4) was meant. The names of the parameters say what each position means: read them before writing the call.
Default values
Sometimes a parameter has a sensible value when the caller gives none. Write it after an = in the brackets. This is called a default parameter:
function greet(name = "Guest") {
return `Namaste, ${name}`;
}
console.log(greet("Asha"), greet(), greet(undefined), greet(null));
Namaste, Asha Namaste, Guest Namaste, Guest Namaste, null
The default is used when the argument is missing, and also when it is undefined, since a missing argument is undefined. It is not used for null: a caller who passes null has said "nothing, on purpose", and gets exactly that. This is the same line that ?? draws between missing and empty in the conditionals lesson.
A parameter is a name inside the function
A parameter works like a name made with let, but only inside the function's body. Outside, it does not exist. The next lesson, on scope, is about where each name can be seen; for now, keep each parameter's use inside its own function.
Worked example 2
A sweet shop sells boxes of laddoos. Write a function that prints the bill line for any number of boxes at any price, such as 3 boxes at ₹250 is ₹750, and call it for two orders.
What we have: a number of boxes and a price for each box, different for each order
What we need: one function that prints the line for any order
The plan: make the two changing values parameters, and build the line with a template literal
function billLine(boxes, price) {
console.log(`${boxes} boxes at ₹${price} is ₹${boxes * price}`);
}
billLine(3, 250);
billLine(5, 180);
3 boxes at ₹250 is ₹750
5 boxes at ₹180 is ₹900
- Each call fills the two gaps with its own arguments, in order: boxes first, price second.
3 boxes at ₹250 is ₹750 and 5 boxes at ₹180 is ₹900.
Check: 3 × 250 = 750 and 5 × 180 = 900.
A path that fails: writing billLine(250, 3). It prints 250 boxes at ₹3 is ₹750: the total is the same, so a check of the total alone passes, while the line itself is nonsense.
Worked example 3
A cab app adds a booking fee of ₹30 to every ride, except for a few rides that have a fee of their own. Write a function that gives the fare for a distance in kilometres at ₹12 a kilometre, with the booking fee as a default parameter.
What we have: a distance, a rate of ₹12 a kilometre, and a fee that is usually 30
What we need: the fare, with the usual fee when none is given
The plan: make the fee a default parameter, so that most calls can leave it out
function fare(km, fee = 30) {
return km * 12 + fee;
}
console.log(fare(10), fare(10, 0), fare(5));
150 120 90
- fare(10) leaves the fee out, so it is 30: 10 × 12 + 30 = 150. fare(10, 0) gives a fee of 0, which is used as given: 120.
The fares are ₹150, ₹120 and ₹90.
Check: 5 × 12 + 30 is 90, and a fee of 0 is kept, because a default replaces only a missing value.
Another way: put the fee in a const outside the function, such as const BOOKING_FEE = 30;, and use it as the default: fee = BOOKING_FEE. The number then lives in one place, with a name.
When you are stuck: a function gives NaN or undefined
Print each parameter as the first line of the body: console.log(km, fee);. A missing argument shows as undefined.
Count the arguments in the call against the parameters in the declaration, and check their order.
If a parameter should have a usual value, give it a default.
Remember that null is passed through as it is; only undefined takes the default.
Your turn
function label(item, qty = 1) {
return `${qty} × ${item}`;
}
console.log(label("samosa"), label("chai", 2), label("vada", undefined));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
1 × samosa 2 × chai 1 × vada
- label("samosa") leaves qty out, so it is 1.
- label("chai", 2) gives qty as 2.
- undefined counts as missing, so qty is 1 again.
It prints 1 × samosa 2 × chai 1 × vada.
In function power(base, exp) { return base ** exp; }, which are the parameters, and which are the arguments in power(2, 10)?Tap to reveal
- The parameters are the names in the declaration: base and exp.
- The arguments are the values in the call: 2 and 10.
Parameters base and exp; arguments 2 and 10, and the call gives 1024.
Write a function welcome(name, city = "Pune") that returns a line such as Welcome, Asha from Pune, and call it with and without a city.Tap to reveal
function welcome(name, city = "Pune") {
return `Welcome, ${name} from ${city}`;
}
console.log(welcome("Asha"));
console.log(welcome("Ravi", "Nagpur"));
Welcome, Asha from Pune
Welcome, Ravi from Nagpur
Without a city it uses Pune; with one, it uses the city given.
Did you know?
Defaults fill only undefined
A default value fills a gap only when the gap is undefined. MDN says default parameters are used if no value or undefined is passed, and the standard's steps agree: the default is worked out only when the value is undefined. So greet(null) does not get "Guest". The null is passed in as a real value, and the greeting says Hello, null.
Why it fits here: It sharpens this topic's rule on defaults: an empty gap gets the default, but a null is a value, and it is used as given.
Sources: MDN: Default parameters; ECMAScript Language Specification: IteratorBindingInitialization
In one line
Parameters are the gaps in a function's declaration, and arguments are the values a call puts in them, matched by position. A missing argument is undefined and an extra one is ignored. A default, as in name = "Guest", fills a gap left empty.
Values coming out: return
At a glance
Ask a shopkeeper the price of a kilo of onions, and you hear a number. You can then add it to the price of tomatoes, or decide it is too dear. A function can give an answer back in the same way, so that the caller can use it.
The return statement ends a function and hands a value back, so a call can be used like the value itself. The method console.log only shows a value, and a function with no return gives undefined. Keep the value on the same line as return, and keep most functions pure.
Take a guess: What does a function give back if it has no return statement?
Ask a shopkeeper the price of a kilo of onions, and you hear a number. You can then do something with it: add it to the price of tomatoes, or decide it is too dear. A function can give an answer back in the same way, so that the caller can use it.
A statement inside a function that ends the function and gives a value back to the caller: return price * 118 / 100;. The call then stands for that value, as if the call were replaced by its answer.
function addGst(price) {
return price * 118 / 100;
}
const total = addGst(100);
console.log(total, addGst(250) + addGst(50));
118 354
The call addGst(100) is replaced by its answer, 118, which goes into total. In the second part, each call is replaced by its answer, 295 and 59, and the two are added: 354. A function that returns can be used anywhere a value can: in a sum, in a template literal, in a condition, or as the argument of another call.
return is not console.log
This is the most common confusion of all with functions. console.log shows a value to a person, on the screen. return hands a value to the program, so that it can carry on working with it. They look alike when you test a function by itself, and they are completely different jobs.
function addGst(price) {
console.log(price * 1.18);
}
const total = addGst(100);
console.log(total);
118
undefined
This version prints 118, so it seems to work. But it gives nothing back, so total holds undefined, as the second line shows. A function with no return statement always gives back undefined. Use console.log to look at values while you build and test; use return to hand the answer to the code that called.
function nothing() {}
console.log(nothing(), typeof nothing());
undefined undefined
return ends the function
When return runs, the function stops at once. Any lines after it are never reached. This makes return useful for leaving early, when the answer is already known:
function check(age) {
if (age < 0) {
return "not a real age";
}
return age >= 18 ? "adult" : "minor";
console.log("never runs");
}
console.log(check(-3), check(20), check(12));
not a real age adult minor
For −3, the first return runs, and the rest of the body is skipped. For 20 and 12, the if is skipped, and the second return gives adult or minor. The last line of the body never runs for any age. A check at the top of a function that returns early for bad input is called a guard clause; it keeps the main work of the function free of nested ifs.
A common mistake
Putting the value on the line after return. JavaScript ends a return statement at the end of its line when nothing follows it there, so the function returns undefined, and the value on the next line is never reached:
function f() {
return
42;
}
console.log(f());
undefined
This is called automatic semicolon insertion: JavaScript puts in the semicolon you left out, here in the wrong place for you. Keep the value on the same line as return, or start it there with a bracket, as in return (.
Functions that answer a question
A function can return a boolean. Name such a function as a question, with is or has, and it reads like plain English inside an if:
function isAdult(age) {
return age >= 18;
}
const age = 20;
if (isAdult(age)) {
console.log("May vote");
}
console.log(isAdult(15));
May vote
false
Notice that the body is return age >= 18;, not an if that returns true or false. The comparison already gives a boolean, so the function can return it as it is.
Returning, or changing something outside
A function can also change a name outside itself instead of returning. This one adds to a running total:
let total = 0;
function addToTotal(amount) {
total = total + amount;
}
addToTotal(50);
addToTotal(20);
console.log(total);
70
It works, but it hides what it does: nothing in the line addToTotal(50); says that total changed. A change that a function makes outside itself, such as changing a name, printing, or saving a file, is called a side effect. A function that only uses its parameters and returns an answer, with no side effects, is called a pure function. It gives the same answer for the same arguments every time, which makes it easy to test:
function withTax(amount) {
return amount * 1.18;
}
console.log(withTax(100) === withTax(100), withTax(100));
true 118
Programs need some side effects, or they could never print or save anything. A good habit is to keep most functions pure, and put the side effects in a few places where they are easy to find.
Worked example 4
A results portal needs the percentage for each student, rounded to two decimal places, from the marks scored and the maximum marks. Write a function that returns it, and use it in a line of text for a student who scored 412 out of 500.
What we have: the marks scored and the maximum, different for each student
What we need: the percentage as a number, rounded to two places, ready to use elsewhere
The plan: return the rounded percentage, so the caller can print it, compare it or store it
function percentage(scored, max) {
return Math.round(scored / max * 100 * 100) / 100;
}
const p = percentage(412, 500);
console.log(`Percentage: ${p}%`, p >= 75);
Percentage: 82.4% true
- Multiplying by 100 again before rounding, and dividing by 100 after, rounds to two decimal places, as in the values lesson. The function returns a number, so the caller can also compare it: 82.4 >= 75 is true.
The function returns 82.4, and the line reads Percentage: 82.4%.
Check: 412 ÷ 500 = 0.824, and 0.824 × 100 = 82.4.
A path that fails: returning (scored / max * 100).toFixed(2). It gives the string 82.40, which prints well but is no longer a number, so a later p >= 75 converts it back, and p + 5 would join instead of adding.
Worked example 5
A railway booking page must refuse a booking for more than 6 passengers on one ticket, and otherwise return the total fare at ₹450 a passenger. Write the function with a guard clause.
What we have: a number of passengers, a limit of 6 and a fare of 450
What we need: a message for a booking over the limit, and the fare otherwise
The plan: check the limit first and return early; the rest of the body then handles only good bookings
function totalFare(passengers) {
if (passengers > 6) {
return "At most 6 passengers on one ticket";
}
return passengers * 450;
}
console.log(totalFare(4), totalFare(8));
1800 At most 6 passengers on one ticket
- For 8 passengers the guard returns its message, and the multiplication never runs.
₹1800 for 4 passengers, and the message for 8.
Check: 4 × 450 = 1800, and a booking of exactly 6 is allowed, as 6 > 6 is false.
Another way: a function that sometimes returns a string and sometimes a number makes its caller check which it got. Many programs return a number every time and report a refusal some other way, such as by throwing an error, which the errors lesson of this track explains.
When you are stuck: a function gives back undefined
Look for a return statement. A function without one gives back undefined, even if it prints the right answer.
Check that the value is on the same line as return.
Check every path: an if that returns in one branch must return in the other too, or that path gives undefined.
Print the call itself: console.log(percentage(412, 500));.
Your turn
function double(n) {
return n * 2;
}
function show(n) {
console.log(n * 2);
}
const a = double(5);
const b = show(5);
console.log(a, b);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
10
10 undefined
- double returns 10, which goes into a; nothing is printed yet.
- show prints 10, and returns nothing, so b is undefined.
- The last line prints a and b: 10 undefined.
It prints 10, then 10 undefined.
Write a function isEven(n) that returns true for an even number, in one line of body, and test it with 4 and 7.Tap to reveal
- A number is even when its remainder after dividing by 2 is 0. The comparison already gives a boolean.
function isEven(n) {
return n % 2 === 0;
}
console.log(isEven(4), isEven(7));
true false
return n % 2 === 0; gives true for 4 and false for 7.
Why does function f() { return; console.log("hi"); } never print hi?Tap to reveal
- return ends the function at once.
- The console.log comes after it, so it is never reached.
Because return ends the function before the line that prints.
Did you know?
A return that returns nothing
A return and its value must share a line. The standard's grammar forbids a line break between the return keyword and the expression to be returned. If the value starts on the next line, automatic semicolon insertion turns the first line into return; on its own. MDN spells out the result: the function returns undefined, and the expression below is never evaluated.
Why it fits here: It is the reason for this topic's rule to keep the value on the same line as return.
Sources: ECMAScript Language Specification: Rules of Automatic Semicolon Insertion; MDN: return
The undefined after console.log
In the Console, console.log("hi") prints hi and then the word undefined. Chrome's guide explains why: the Console is a REPL, which reads your code, evaluates it, prints the result of your expression and loops. MDN lists console.log's return value as none, undefined. So the first line is what the function showed, and the second is what it gave back.
Why it fits here: It shows this topic's difference between showing and returning in one place: console.log shows a value but gives back nothing.
Sources: Chrome for Developers: Run JavaScript in the Console; MDN: console.log(); ECMAScript Language Specification: The return Statement
In one line
return ends a function and hands a value back, so a call can be used like the value itself. console.log only shows a value; a function with no return gives undefined. Keep the value on the return's own line, and keep most functions pure.
Functions as values: expressions and arrows
At a glance
In JavaScript a function is a value, like a number or a string. It can be stored in a name, passed to another function, or given back by one, which is why the language is said to have first-class functions.
So a function can be made as a function expression and kept in a const, or as an arrow, such as n => n * 2, which returns its one expression without the word return. With braces, an arrow needs return. A declaration can be called above its line; an expression only below.
Take a guess: Does n => n * 2 need the word return to give back its answer?
In JavaScript a function is a value, like a number or a string. typeof gives it a type of its own, function, and it can be stored in a name, passed to another function, or given back by one. A language in which functions are values like this is said to have first-class functions.
Because a function is a value, there is a second way to make one: write the function where a value is expected, and keep it in a name.
A function written where a value is expected, as in const add = function (a, b) { return a + b; };. It has no name of its own after the word function; the const gives it one.
const add = function (a, b) {
return a + b;
};
console.log(add(2, 3), typeof add);
5 function
A function with no name of its own is called an anonymous function. It is called through the name that holds it, as add is here, exactly like a declared function. The semicolon after the closing brace ends the const statement, as it would after any value.
Arrow functions
Since 2015, JavaScript has a shorter way to write a function expression, with the arrow =>, read aloud as "goes to" or "gives".
A short function expression: the parameters, then =>, then the body. (a, b) => a + b is read "a and b give a plus b".
const add = (a, b) => a + b;
const double = n => n * 2;
const hello = () => "hello";
console.log(add(2, 3), double(21), hello());
5 42 hello
Three short forms are at work here. When the body is a single expression with no braces, its value is returned without the word return: this is called an implicit return. With exactly one parameter, the round brackets may be left out, as in n => n * 2. With no parameters, the brackets stay, empty, as in () => "hello".
When the body needs more than one line, use braces. But then it is an ordinary body, and the implicit return is gone: you must write return yourself.
const square = (n) => {
const result = n * n;
return result;
};
console.log(square(9));
81
A common mistake
Adding braces to a one-line arrow and forgetting the return. With braces, n * n; is worked out and thrown away, and the function gives back undefined:
const broken = (n) => {
n * n;
};
console.log(broken(9));
undefined
| Form | Example | Gives back |
|---|---|---|
| declaration | function double(n) { return n * 2; } | what return gives |
| function expression | const double = function (n) { return n * 2; }; | what return gives |
| arrow, no braces | const double = n => n * 2; | the expression, without return |
| arrow, with braces | const double = n => { return n * 2; }; | what return gives, so return is needed |
Arrow functions also differ from the others in what the word this means inside them. That matters only for methods of objects, which the objects lesson of this track explains, and the modern JavaScript step returns to arrows in full.
Where each can be called
A declaration and an expression differ in one more way: where in the program they can be called. A function declaration can be called above the line where it is written. Before any code runs, JavaScript reads the whole program and makes every declared function ready, the hoisting that the values lesson met with var.
console.log(twice(4));
function twice(n) {
return n * 2;
}
8
A function expression is a value put into a name, so it exists only once its line has run. Called above that line, it gives the errors that any name gives there. With const it is the temporal dead zone; with var, the name exists but holds undefined, and undefined cannot be called:
console.log(twice(4));
const twice = function (n) {
return n * 2;
};
Uncaught ReferenceError: Cannot access 'twice' before initialization
at line 1
console.log(twice(4));
var twice = function (n) {
return n * 2;
};
Uncaught TypeError: twice is not a function
at line 1
Which form should you use? Teams differ, and both are common. A simple rule that keeps programs easy to follow: declare a program's main jobs with function declarations, and use arrow functions for small jobs handed to other functions, which is the subject of the next section. Whichever you choose, define a function above the code that calls it, and the question of where it can be called never arises.
Worked example 6
A canteen's app works out a discounted price in three ways in three files, written by three people. Rewrite the rule "10% off" as a declaration, a function expression and an arrow function, and check that all three agree for ₹250.
What we have: the rule "10% off", and a price of 250
What we need: three functions that give the same answer, 225
The plan: write the same body three ways; the arrow can drop the word return because its body is one expression
function discountA(price) {
return price * 90 / 100;
}
const discountB = function (price) {
return price * 90 / 100;
};
const discountC = (price) => price * 90 / 100;
console.log(discountA(250), discountB(250), discountC(250));
225 225 225
- All three are functions taking one parameter and giving back the same expression.
All three give 225.
Check: 250 × 90 ÷ 100 = 225, which is 250 less its tenth, 25.
A path that fails: writing the arrow with braces and no return, as (price) => { price * 90 / 100; }. It looks like the other two, and gives back undefined.
When you are stuck: an arrow function gives back undefined
If its body has braces, it needs a return. Without braces, it returns its one expression.
To return an object from an arrow with no braces, wrap it in round brackets; the objects lesson shows why.
If a function expression "is not a function" or "cannot be accessed", move its line above the calls.
Print the function itself: console.log(square); shows whether the name holds a function at all.
Your turn
const half = n => n / 2;
const addOne = (n) => {
n + 1;
};
console.log(half(9), addOne(9));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4.5 undefined
- half has no braces, so it returns n / 2: 4.5.
- addOne has braces and no return, so it gives back undefined.
It prints 4.5 undefined.
Rewrite function cube(n) { return n * n * n; } as an arrow function with an implicit return.Tap to reveal
const cube = n => n * n * n;
console.log(cube(3));
27
const cube = n => n * n * n; gives 27 for 3.
A program calls total() on its first line, and total is made lower down with const total = () => 0;. Which error appears, and what is the fix?Tap to reveal
- A const cannot be touched before its line: the temporal dead zone.
- So the message is ReferenceError: Cannot access 'total' before initialization.
- Move the const above the call, or make total a function declaration.
A ReferenceError; define total above the line that calls it.
Did you know?
An object that can be called
Functions are objects, yet typeof gives them a type name of their own. The standard's steps for typeof say: if the value has a [[Call]] internal method, return "function"; otherwise, for an object, return "object". So a function is an object that can be called, and typeof picks out exactly that one ability.
Why it fits here: It explains this topic's opening claim: a function is a value, an object with one extra power, the power to be called.
Source: ECMAScript Language Specification: The typeof Operator
What arrows leave out
Arrow functions are not only shorter. The standard notes that an arrow function does not define its own bindings for arguments, super, this or new.target; inside it, those words mean what they mean in the code around it. MDN puts it the same way, and adds that arrow functions should not be used as methods, and cannot be used as constructors.
Why it fits here: It adds a warning to this topic's arrows: they suit short jobs and callbacks, but not methods that need their own this.
Sources: ECMAScript Language Specification: Arrow Function Definitions; MDN: Arrow function expressions
In one line
A function is a value: keep one in a const with a function expression, or with an arrow such as n => n * 2, which returns its one expression without the word return. With braces, an arrow needs return. A declaration can be called above its line; an expression only below.
Functions passed to functions: callbacks
At a glance
At a wedding, the head cook runs the kitchen but does not decide every dish. For each table she is handed a card, make it mild or make it hot, and at the right moment she follows the card. The steps are hers; the card is the guest's choice.
A callback is a function passed to another function, which calls it when the time comes. Pass the name without brackets, or the function runs at once. A function that takes or gives back a function is called higher-order, and callbacks are how browsers, arrays and Node run your code at the right moment.
Take a guess: Why do you pass a callback's name without brackets?
At a wedding, the caterer's head cook runs the kitchen, but does not decide every dish. For each table she is handed a card: "make it mild", or "make it hot". She follows her own steps, and at the right moment she follows the card. The steps are hers; the card is the guest's choice.
Since a function is a value, it can be handed to another function as an argument, like that card. The function that receives it decides when to call it.
A function passed to another function as an argument, to be called by that function at the right moment. The name says it: the receiving function calls it back.
A function that takes a function as an argument, or gives one back. The receiving function in each example below is a higher-order function.
function shout(text) {
return text.toUpperCase() + "!";
}
function whisper(text) {
return text.toLowerCase() + "...";
}
function say(text, style) {
return style(text);
}
console.log(say("Chai is ready", shout), say("Chai is ready", whisper));
CHAI IS READY! chai is ready...
Look closely at the calls. say("Chai is ready", shout) passes shout without brackets: the function itself, not its answer. Inside say, the parameter style now holds shout, and style(text) calls it. With whisper passed instead, the same say gives a different result. say holds the steps; the callback holds the choice.
A common mistake
Putting brackets on the callback when passing it. say("Chai is ready", shout()) calls shout at once, with no argument, and passes its answer instead of the function. Here, shout has no text to work on, so the program stops with an error before say even starts. Pass the name alone; the receiving function adds the brackets when it is ready.
function shout(text) {
return text.toUpperCase() + "!";
}
function say(text, style) {
return style(text);
}
console.log(say("Chai is ready", shout()));
Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase')
at shout (line 2)
at line 7
Callbacks written on the spot
A callback is often a small arrow function, written right inside the call, with no name of its own. This keeps the choice next to the place where it is used:
const calculate = (a, b, op) => op(a, b);
console.log(calculate(6, 3, (x, y) => x + y), calculate(6, 3, (x, y) => x * y));
9 18
calculate does not know any arithmetic. It takes two numbers and a job, and runs the job on the numbers. The first call hands it an adding job, and the second a multiplying job.
A callback can also be called many times. This helper runs a job a given number of times, passing the round number each time. The loop inside it, for, is the subject of the loops lesson; here, watch only the callback:
function repeat(times, job) {
for (let i = 1; i <= times; i++) {
job(i);
}
}
repeat(3, (n) => console.log(`Round ${n}`));
Round 1
Round 2
Round 3
Callbacks are everywhere in JavaScript. A web page hands the browser a function to run when a button is clicked, which the events lesson of this track teaches. An array hands each of its items to a function, to change or keep or drop them, which the arrays lesson teaches. A program hands Node a function to run when a file has been read. Each time, the pattern is the same: pass the function, and let the receiver call it.
Functions that make functions
A higher-order function can also give back a new function. This one makes a greeter for any greeting:
function makeGreeter(greeting) {
return (name) => `${greeting}, ${name}`;
}
const hindi = makeGreeter("Namaste");
console.log(hindi("Asha"), makeGreeter("Hello")("Ravi"));
Namaste, Asha Hello, Ravi
makeGreeter("Namaste") returns an arrow function that remembers the greeting it was made with, even after makeGreeter has finished. A function that remembers the names around it like this is called a closure. The scope lesson, next, explains how that remembering works.
Worked example 7
A shop's app gives different discounts on different days: 10% off on Mondays, and ₹50 off any bill on Fridays. Write one function that applies a discount rule passed in as a callback, and use it for a bill of ₹800 with each rule.
What we have: a bill of 800, and two discount rules
What we need: one function that takes the bill and a rule, and gives the price after the rule
The plan: make the rule a callback parameter; write each rule as a small arrow function
function finalPrice(bill, rule) {
return rule(bill);
}
const monday = (amount) => amount * 90 / 100;
const friday = (amount) => amount - 50;
console.log(finalPrice(800, monday), finalPrice(800, friday));
720 750
- finalPrice knows nothing about the rules. A new rule for Wednesdays needs only a new small function, and no change to finalPrice.
₹720 with the Monday rule and ₹750 with the Friday rule.
Check: 800 less 10% is 800 − 80 = 720, and 800 − 50 = 750.
A path that fails: writing one function with an if for each day inside it. It works for two days, but every new offer means changing that function, and every change risks breaking the offers that already work.
When you are stuck: a callback does not run, or runs at the wrong time
Check how it is passed: the name alone, shout, passes the function; shout() calls it at once and passes its answer.
Check that the receiving function calls its parameter, with brackets: style(text).
Print the parameter inside the receiver: console.log(typeof style); should say function.
If the callback needs values, check that the receiver passes them in the call: job(i).
Your turn
const apply = (n, f) => f(n);
console.log(apply(5, (x) => x * x), apply(5, (x) => x + 1));
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
25 6
- The first call passes a squaring arrow: 5 × 5 = 25.
- The second passes an adding arrow: 5 + 1 = 6.
It prints 25 6.
What is the difference between run(task) and run(task())?Tap to reveal
- run(task) passes the function task itself, to be called by run.
- run(task()) calls task first, and passes whatever task returned.
The first passes the function; the second passes its answer.
Write twice(f, x), which calls f on x and then calls f again on the answer, and test it with an arrow that adds 3, starting from 10.Tap to reveal
const twice = (f, x) => f(f(x));
console.log(twice((n) => n + 3, 10));
16
10 + 3 = 13, then 13 + 3 = 16.
Did you know?
Don't call us, we'll call you
Callbacks turn the usual order round: your code does not call the library; the library calls your code. Martin Fowler calls this inversion of control, also known as the Hollywood Principle: don't call us, we'll call you. He traces the colourful name to a 1983 paper by Richard Sweet on Mesa, which lists it among its design goals.
Why it fits here: It names what this topic's callbacks do: you hand over a function, and the browser or the array calls it when the time comes.
Zero is never quite now
A browser keeps its own rules for when to call back. The HTML standard says that once timers are nested more than five deep, a timeout of less than 4 milliseconds becomes 4. MDN describes the effect: after a nested setTimeout has been scheduled 5 times, browsers enforce a minimum of 4 milliseconds. So a delay of 0 never quite means now.
Why it fits here: It is a reminder from this topic: a callback runs when its caller decides, and the caller may be the browser, with its own clock.
In one line
A callback is a function passed to another function, which calls it when the time comes; pass the name without brackets. A function that takes or gives back a function is higher-order, and callbacks are how browsers, arrays and Node run your code at the right moment.
Functions calling functions: the call stack
At a glance
A big job is easier as several small ones. A bill is a subtotal plus delivery, and a subtotal is a price times a quantity. Each small job can be a function, and the big job's function calls the small ones.
The call stack keeps the waiting functions in order, the newest on top. A stack trace is that stack at the moment of an error: read it from the top, then follow the callers down. A function that calls itself needs a base case to stop, and each function should do one job.
Take a guess: What happens to a function that calls itself and never stops?
A big job is easier as several small ones. A bill is a subtotal plus delivery; a subtotal is a price times a quantity. Each small job can be a function, and the big job's function calls the small ones.
function subtotal(price, qty) {
return price * qty;
}
function bill(price, qty) {
return subtotal(price, qty) + 40;
}
console.log(bill(120, 3));
400
Follow the calls in order. The last line calls bill. Inside bill, the call to subtotal runs first, and gives back 360. bill adds 40 and gives back 400, and console.log prints it. Each function waited for the one it called to finish before carrying on.
The list JavaScript keeps of the functions that are running and waiting, newest on top. A call puts a function on top of the stack; a return takes it off, and the function below carries on where it left off.
Picture a pile of plates at a wedding buffet. The last plate put on the pile is the first one taken off. Calls work the same way: when bill calls subtotal, subtotal goes on top of bill. Only the top function runs. When subtotal returns, it comes off, and bill, now on top again, carries on.
Reading a trace
When an error stops a program inside a function, the message is followed by a trace: the call stack at the moment of the error, written top first. Each line says which function was running, and at which line. You met short traces in the Learning to learn step; with functions, they grow:
function inner() {
null.x;
}
function outer() {
inner();
}
outer();
Uncaught TypeError: Cannot read properties of null (reading 'x')
at inner (line 2)
at outer (line 5)
at line 7
Read it from the top. The error happened in inner, at line 2. inner had been called by outer, at line 5. outer had been called from the program itself, at line 7, which is the line with no function's name. The top line is where the slip is, or where it showed; the lines below say how the program got there. When the top line is inside a function that many places call, the line below it says which caller sent the bad value.
Not every slip stops the program. A misspelt property gives undefined, and the arithmetic goes on quietly with it. No error and no trace, only a wrong answer:
function total(prices) {
return prices.lenght * 2;
}
function report() {
return total([1, 2]).toFixed(2);
}
console.log(report());
NaN
Here length is spelt lenght, which gives undefined, and undefined × 2 is NaN. With no trace to follow, the method of the Learning to learn step takes over: print what each function returns, from the inside out, until the first wrong value appears.
A function that calls itself
A function may call itself. This is called recursion. Each call is a new item on the stack, with its own parameters, so the function can work on a smaller piece of the job each time, until it reaches a case it can answer at once:
function countDown(n) {
if (n === 0) {
return "Go!";
}
return countDown(n - 1);
}
console.log(countDown(3));
Go!
countDown(3) calls countDown(2), which calls countDown(1), which calls countDown(0). That one returns "Go!" at once, and each call below it returns the same answer in turn. The case that stops the calls, here n === 0, is called the base case. Without one, the calls never stop, the stack grows until JavaScript's limit, and the program ends with a RangeError. The function below is written on a single line, so that every line of its trace names the same place; the page shows the first ten:
function forever(n) { return forever(n + 1); }
forever(1);
Uncaught RangeError: Maximum call stack size exceeded
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
Recursion returns in the data structures and algorithms step, where it walks trees and sorts lists. For now, remember the shape of its error: one function's name, repeated down the whole trace.
One job each
Splitting work into functions pays off only if each function has one clear job. A useful test: describe the function in one sentence without the word "and". "subtotal gives the price times the quantity" passes. "handleOrder works out the bill and prints the receipt and saves the order" does not, and is three functions waiting to be separated.
- A function with one job can be tested alone, with chosen arguments.
- Its name can say exactly what it does, so a reader can skip its body.
- A trace that names it points to one job, not to a tangle.
Worked example 8
A food app's bill is the price times the quantity, plus 5% GST on that, plus ₹40 delivery. Build it from three small functions, and work out the bill for 3 thalis at ₹120.
What we have: a price of 120, a quantity of 3, a GST rate of 5% and a delivery fee of 40
What we need: the bill, built from small functions that each do one job
The plan: write subtotal, then gst on a subtotal, then bill, which calls the other two and adds delivery
function subtotal(price, qty) {
return price * qty;
}
function gst(amount) {
return amount * 5 / 100;
}
function bill(price, qty) {
const sub = subtotal(price, qty);
return sub + gst(sub) + 40;
}
console.log(subtotal(120, 3), gst(360), bill(120, 3));
360 18 418
- Each function was checked on its own first: subtotal gives 360 and gst gives 18. bill then only joins answers that are already known to be right.
The bill is ₹418.
Check: 3 × 120 = 360; 5% of 360 is 18; 360 + 18 + 40 = 418.
A path that fails: writing the whole bill as one line, price * qty * 1.05 + 40. It gives 418 here, but when the bill comes out wrong one day there is nothing to test piece by piece, and nothing for a trace to name.
When you are stuck: an error appears inside a function
Read the trace from the top: the first line is where it stopped, and each line below is a caller.
Follow the bad value down the trace to the caller that sent it.
For a RangeError with one name repeated, look for a missing or unreachable base case.
With no error and a wrong answer, print what each function returns, from the innermost out.
Your turn
function a() {
return b() + 1;
}
function b() {
return c() * 2;
}
function c() {
return 5;
}
console.log(a());
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
11
- a calls b, which calls c.
- c returns 5, so b returns 5 × 2 = 10.
- a returns 10 + 1 = 11.
It prints 11.
A trace reads: at price (line 3), at cart (line 9), at line 14. Where did the error happen, and who called that function?Tap to reveal
- The top line is where it happened: inside price, at line 3.
- The next line is the caller: cart, at line 9.
- The last line is the program's own code, which called cart at line 14.
It happened in price, at line 3, which cart called at line 9.
Write a recursive function sumTo(n) that gives 1 + 2 + ... + n, with the base case n === 0, and test it with 4.Tap to reveal
- The base case: the sum up to 0 is 0.
- Otherwise the sum up to n is n plus the sum up to n − 1.
function sumTo(n) {
if (n === 0) {
return 0;
}
return n + sumTo(n - 1);
}
console.log(sumTo(4));
10
sumTo(4) is 4 + 3 + 2 + 1 + 0 = 10.
Did you know?
The operational cellar
The stack has inventors. Klaus Samelson and Friedrich L. Bauer of the Technical University of Munich proposed a stack, which they called Operationskeller, the operational cellar, in 1955, and filed a patent in 1957. In 1988 Bauer received the IEEE Computer Pioneer Award, whose citation reads: For computer stacks.
Why it fits here: Every call in this topic is pushed onto such a stack and taken off again, newest first.
Sources: Wikipedia: Stack (abstract data type); IEEE Computer Society: Friedrich L. Bauer
Calls that reuse their frame
Some recursion need not grow the stack. ECMAScript 6 added Proper Tail Calls: a call made in tail position reuses the stack space of the calling function, instead of adding a new frame. When WebKit described its version in May 2016, it noted that for deeply recursive code, PTC enables code to run that would otherwise throw a stack overflow exception.
Why it fits here: It explains why the stack in this topic can overflow: each ordinary call adds a frame, and only special tail calls can reuse one.
In one line
Functions can call functions, and the call stack keeps the waiting ones in order, newest on top. A trace is that stack at the moment of an error: read it from the top, then follow the callers down. Recursion needs a base case, and each function should do one job.
Where it is used
Every program larger than a few lines is built from functions. Here is where each idea of this lesson shows up in real work.
| What you learned | Where it is used | A real example |
|---|---|---|
| function declarations | every rule a program follows | one function for the GST on a bill, called by the cart, the invoice and the refund |
| parameters and defaults | jobs that change a little each time | a fare function with the distance as a parameter and a usual booking fee as a default |
return | every function whose answer is used again | a percentage that the portal prints, compares and stores |
| guard clauses | checking input before work starts | a booking function that refuses more than 6 passengers before adding up any fare |
| arrow functions | small jobs, written where they are used | the rule for sorting a contacts list by name |
| callbacks | code the browser or Node runs later | a function the page runs when a button is clicked; a function Node runs when a file has been read |
| higher-order functions | one function, many rules | a price function that takes the day's discount rule |
| the call stack and traces | finding where a program stopped | a server's error log names the function that failed and every function that called it |
| one job per function | code that a team can test and change | subtotal, gst and bill, each tested on its own |
Mistakes and debugging
These are the slips that people meet most often with functions. Every output below is the real one, from the code shown.
1. Printing instead of returning
function addGst(price) {
console.log(price * 1.18);
}
const total = addGst(100);
console.log(total);
118
undefined
No error: the function shows the answer and gives back nothing. The fix: return price * 118 / 100;.
2. A return with its value on the next line
function f() {
return
42;
}
console.log(f());
undefined
No error: the return ends at its own line. The fix: keep the value on the same line as return.
3. Braces on an arrow, and no return
const square = (n) => {
n * n;
};
console.log(square(9));
undefined
No error: with braces, the body needs its own return. The fix: (n) => n * n, or { return n * n; }.
4. A missing argument
function area(length, width) {
return length * width;
}
console.log(area(4));
NaN
No error: width is undefined, and the arithmetic gives NaN. The fix: pass every argument, or give the parameter a default.
5. Calling a function expression too early
console.log(twice(4));
const twice = (n) => n * 2;
Uncaught ReferenceError: Cannot access 'twice' before initialization
at line 1
The fix: define the function above the calls, or make it a function declaration.
6. Calling something that is not a function
const price = 100;
price();
Uncaught TypeError: price is not a function
at line 2
The fix: print typeof price; the name holds a value of another type, or a function's name was reused for something else.
7. Brackets on a callback
function shout(text) {
return text.toUpperCase();
}
function say(text, style) {
return style(text);
}
console.log(say("hi", shout()));
Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase')
at shout (line 2)
at line 7
The fix: pass shout, not shout(). The trace's last line shows that shout was called from the program itself, at line 7, before say ever ran.
8. A comma left out between arguments
function area(length, width) {
return length * width;
}
console.log(area(5 3));
Uncaught SyntaxError: missing ) after argument list
The fix: area(5, 3). Finding no comma, JavaScript expected the list of arguments to end, as in the Learning to learn step.
9. A function that never stops calling itself
function forever(n) { return forever(n + 1); }
forever(1);
Uncaught RangeError: Maximum call stack size exceeded
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
at forever (line 1)
The fix: give it a base case that returns without calling itself, and check that every call moves towards that case.
The debugging corner: what goes in, what comes out
For any function that gives a wrong answer, print its arguments as the first line of its body, and its answer just before each return. One of the two is not what you expected, and that tells you whether to look at the caller or at the function. In the Sources panel of the DevTools step, Step into does the same at a breakpoint: it walks into the call, and the Scope pane shows each parameter's value.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
// declare once, call often; parameters with defaults; return gives the answer back
function fare(km, fee = 30) {
if (km <= 0) {
return 0;
}
return km * 12 + fee;
}
console.log(fare(10), fare(10, 0), fare(-1));
// function expressions and arrows; an arrow with no braces returns its expression
const double = function (n) {
return n * 2;
};
const half = (n) => n / 2;
console.log(double(21), half(9));
// a callback is a function passed in, by name, without brackets
const applyTo = (n, job) => job(n);
console.log(applyTo(5, half), applyTo(5, (x) => x * x));
// functions calling functions: the trace lists them, newest first
function gst(amount) {
return amount * 5 / 100;
}
function bill(price, qty) {
return price * qty + gst(price * qty);
}
console.log(bill(120, 3));
150 120 0
42 4.5
2.5 25
378
| When you see | It means | Look at |
|---|---|---|
| undefined from a call | no return, or a return on its own line | the function's return statements |
| NaN from a call | a missing argument, or a misspelt property | the call's arguments, and the body's names |
ReferenceError: Cannot access '...' before initialization | a function expression called above its line | move it up, or declare it |
TypeError: ... is not a function | brackets after a value that is not a function | typeof of the name |
Cannot read properties of undefined inside a callback | the callback was called with brackets when it was passed | pass the name alone |
RangeError: Maximum call stack size exceeded | a function that never stops calling itself | its base case |
| a trace with several lines | the calls that led to the error, newest first | the top line first, then the callers |
The story: One rule, one place
You write the fare rule once, as a job with a name of its own. It takes the line and the passenger, and gives back the fare. Then you cross out all seven copies, and in each place you write a single line that asks the job for the answer.
The gates open together, and every passenger on the harbour line pays ₹6. Nobody in either queue is cheated.
Master Verge nods at the one line that holds the rule. "Next month the fare will change again," he says. "Now you will change it once."
Reagents gathered: function, parameter, return, arrow function, callback, call stack.
Sources
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- The ECMAScript language specification (ECMA-262) (Ecma International copyright; facts and ideas only)