Learn / Lesson 7 of 10
Functions
Package steps into a reusable recipe that takes inputs and returns an answer.
Words on this page, in plain English (9)Open if any word is new to you
- Variable
- A labelled box that holds a value. You give it a name, put something in it, and use the name later to get it back.
- Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- If (a decision)
- Runs some code only when something is true. Like: if it's raining, take an umbrella.
- Loop
- Code that repeats. A
forloop repeats once per item or a set number of times; awhileloop repeats as long as something stays true. - Function
- A named, reusable recipe. You give it ingredients (inputs), it does its steps, and hands back a result.
- Parameter (input)
- A name for an ingredient a function receives. In
double(n),nis the parameter; when you calldouble(5), it holds 5. - Return
- How a function hands back its answer. As soon as
returnruns, the function stops. - console.log
- Prints something so you can see it. The easiest way to find out what your code is really doing.
- Test
- An example input with the answer it should give. Your code passes if it gives that answer.
A reusable recipe
A function is a named recipe: a block of code you write once and run whenever you need it. It can take inputs, called parameters, and hand back a result with return:
Try it: a function
function double(n) {
return n * 2;
}
console.log(double(4));
console.log(double(10));
console.log(double(double(3))); // the result of one call feeds the nextPress Run to see the output. You can change the code first.
function double(n)defines the recipe.nis the parameter: a name for whatever value is passed in.double(4)calls it: runs the recipe withnset to 4.return n * 2ends the function and hands back the result.
Every problem on this site asks you to write one function. The tests call it with different inputs and check what it returns.
More than one parameter
Separate parameters with commas. Values are matched up in order:
Try it: two parameters
function area(width, height) {
return width * height;
}
console.log(area(3, 4));
console.log(area(10, 2));Press Run to see the output. You can change the code first.
return vs console.log
This trips up almost every beginner. console.log shows a value to you. return hands it back to the code that called the function. Only return gives the caller something to use:
Try it: the difference
function showSum(a, b) {
console.log(a + b); // shows it... but gives nothing back
}
function giveSum(a, b) {
return a + b; // hands it back
}
const x = showSum(2, 3);
const y = giveSum(2, 3);
console.log("x is", x);
console.log("y is", y);Press Run to see the output. You can change the code first.
showSum printed 5, but x is undefined: a function with no return gives back undefined. When a problem's test says your answer was undefined, a missing return is the usual reason.
return ends the function
As soon as return runs, the function stops. That's useful for leaving early once you know the answer:
Try it: leaving early
function firstNegative(nums) {
for (const n of nums) {
if (n < 0) return n; // found it: stop right here
}
return null; // only reached if nothing was negative
}
console.log(firstNegative([4, 7, -2, 9, -5]));
console.log(firstNegative([1, 2, 3]));Press Run to see the output. You can change the code first.
Variables inside a function stay inside
Variables created inside a function only exist inside it. Each call gets fresh ones. That keeps functions from accidentally interfering with each other:
Try it: inside stays inside
function makeTotal(prices) {
let total = 0;
for (const p of prices) total += p;
return total;
}
console.log(makeTotal([1, 2, 3]));
console.log(makeTotal([10, 20]));
console.log(total); // there is no total out herePress Run to see the output. You can change the code first.
total += p is short for total = total + p.
Helper functions
Big problems get easier when you split them into small functions with clear names. A function can call another:
Try it: helpers
function isVowel(letter) {
return "aeiou".includes(letter);
}
function countVowels(word) {
let count = 0;
for (const letter of word.toLowerCase()) {
if (isVowel(letter)) count++;
}
return count;
}
console.log(countVowels("Programming"));Press Run to see the output. You can change the code first.
Arrow functions
You'll also see a shorter way to write small functions, with =>. These two are the same:
function triple(n) { return n * 3;}const triple = (n) => n * 3;Arrow functions are common when passing a small function to another, like list.sort((a, b) => a - b): "to compare two items, subtract them".
Your turn
Write a function biggest(nums) that returns the biggest number in a list, using a loop (not Math.max). Test it on a few lists, including one with only negative numbers.
Your turn
function biggest(nums) {
}
console.log(biggest([3, 9, 2]));
console.log(biggest([-5, -1, -8]));Press Run to see the output. You can change the code first.
What you learned
- A function is a named, reusable recipe:
function name(params) { ... }. - Call it with
name(values). returnhands a value back and ends the function; without it, you getundefined.console.logonly shows; it doesn't give anything back.- Variables inside a function stay inside.