10 / 12 · Intro
Functions
Write function square(n) { return n * n; } once, and square(4) gives 16, square(9) gives 81, and so on for any number you pass in.
Jump to the 10 practice questionsYou will learn
- Define a function and call it with arguments
- Use default parameters and arrow functions
Before this: Arrays in JavaScript
1Explain
Naming a piece of work
The definition starts with the keyword function, then the function's name, then a list of parameters in parentheses. A parameter is a variable that receives a value when the function is called; here it is name. The body in curly braces does the work. When you call greet("Ana"), the value "Ana", called an argument, is placed into the parameter name, and the body runs.
Each call opens a box "inside greet()" where name holds the argument; return sends the text back to the call.
function greet(name) {return "Hello, " + name + "!";}console.log(greet("Ana")); // Hello, Ana!console.log(greet("Ji")); // Hello, Ji!
Hello, Ana! Hello, Ji!
2Problem
double(7)
What does this print?
function double(n) {
return n * 2;
}
console.log(double(7));Hint
7 goes into n.
Solution
Answer: 14
7 is passed in as n, and 7 × 2 = 14 is returned.
3Explain
return is not printing
Returning a value and printing it are different things, and beginners often mix them up. A function that only calls console.log shows something on the screen, but hands nothing back. Its call evaluates to undefined, so you cannot use the result in a calculation. As a rule, let functions return results and let the code that calls them decide whether to print.
add hands 5 back, so add(2, 3) * 10 can use it. addPrint only shows 5 and hands back nothing.
function addPrint(a, b) {console.log(a + b);}function add(a, b) {return a + b;}const x = add(2, 3) * 10;console.log(x); // 50addPrint(2, 3); // prints 5, but returns nothing usable
50 5
4Problem
A function that only prints
What does this print?
function show(n) {
console.log(n);
}
const r = show(5);
console.log(typeof r);Hint
show has no return line.
Solution
Answer: 5, then undefined
show prints 5 but returns nothing, so r is undefined and its type is "undefined".
5Explore
Arguments and a default
A function can take several parameters, separated by commas, and the arguments are matched in order: in add(2, 3), a is 2 and b is 3. If a call leaves out an argument, that parameter is undefined. You can give a parameter a default value that is used when nothing is passed: function tip(bill, rate = 0.15) uses 0.15 unless the caller supplies another rate.
Arguments fill the parameters in order. When rate is left out, its default 0.1 is used.
function tip(bill, rate = 0.1) {
return bill * rate;
}
console.log(tip(50));56Problem
The default rate
What does this print?
function tip(bill, rate = 0.1) {
return bill * rate;
}
console.log(tip(50));Hint
Only one argument is passed.
Solution
Answer: 5
No rate is passed, so the default 0.1 is used: 50 × 0.1 = 5.
7Explain
Arrow functions
Modern JavaScript also has a shorter way to write small functions, the arrow function. const square = (n) => n * n; means the same as the square function in the lead. When the body is a single expression, its value is returned automatically, with no braces and no return keyword. You will see arrow functions everywhere in modern code.
const square = (n) => n * n;
const add = (a, b) => a + b;
console.log(square(4), add(2, 3));16 58Problem
Three possible returns
function sign(n) {
if (n < 0) return "neg";
if (n === 0) return "zero";
return "pos";
}
console.log(sign(0));Hint
Follow sign(0) to its first return.
Solution
Answer: zero
0 < 0 is false, 0 === 0 is true, so "zero" is returned.
9Practice
Fix square
Fix the body so square returns n times n. The program should print 16 and 81.
16
81function square(n) {
return 0;
}
console.log(square(4));
console.log(square(9));
Hint
return n * n; and nothing else in the body.
A solution
function square(n) {
return n * n;
}
console.log(square(4));
console.log(square(9));10Practice
isEven as an arrow function
Change the arrow function so it returns true for even numbers and false for odd ones.
true
falseconst isEven = (n) => false;
console.log(isEven(10));
console.log(isEven(7));
Hint
An even number leaves remainder 0: n % 2 === 0.
A solution
const isEven = (n) => n % 2 === 0;
console.log(isEven(10));
console.log(isEven(7));11Practice
Write clamp(n, low, high)
Finish clamp so that it returns n, but never less than low and never more than high. Each test calls your function and prints what it returns.
| Test | Runs after your code | Expected output |
|---|---|---|
| 1 | console.log(clamp(5, 0, 10)); | 5 |
| 2 | console.log(clamp(-3, 0, 10)); | 0 |
| 3 | console.log(clamp(12, 0, 10)); | 10 |
| 4 | console.log(clamp(0, 0, 10)); | 0 |
function clamp(n, low, high) {
return n;
}
Hint
Two early returns handle the cases below low and above high; the last line returns n unchanged.
A solution
function clamp(n, low, high) {
if (n < low) return low;
if (n > high) return high;
return n;
}12Explain
Common mistakes
function add(a, b) {
return a + b;
}
console.log(ad(2, 3));ReferenceError: ad is not defined (line 4)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
The call is misspelled: ad is not the name that was defined.
function f() {
const secret = 42;
}
f();
console.log(secret);ReferenceError: secret is not defined (line 5)
- The word before the colon names the kind of error: ReferenceError, TypeError, SyntaxError.
- After the colon: what went wrong, usually with the name involved.
- The line number shows where the program stopped. A SyntaxError stops it before any line runs.
A variable made inside a function exists only inside it. Return the value if the rest of the program needs it.
13
Summary
- function name(params) { ... } defines; name(args) calls.
- Arguments are matched to parameters in order.
- return ends the function and hands back a value; printing is not returning.
- Default parameters fill in missing arguments.
- Arrow functions: (n) => n * n.
- Variables inside a function stay inside (scope).