Reusable code
Do more with functions
Lesson 6 of 20 · 7 min · Module 2: Decisions & reusable work
A function is a recipe you can use again and again. Give it an input, let it do its thing, and get an output.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Define parameters and a return value
- Call the same function with different inputs
- Apply a function to every array item
The idea
Parameters are the names for inputs. The return keyword sends a value back. An array’s map() method runs a function for each item.
function square(number) {
return number * number;
}
console.log(square(4)); // 16
01A parameter is a local name
In double(number), number is supplied by the caller. Returning number * 2 works with different inputs; returning a fixed value only solves one example.
function double(number) { return number * 2; }
console.log(double(3));
console.log(double(5));6
1002Pass a function, not one result
numbers.map(double) gives map the function to call for each item. numbers.map(double()) would call double immediately without an argument and pass its result instead.
Your turn
double(number) to return twice its input. Then create doubled by doubling each number in [1, 2, 3].What the checks look for
- double works for positive numbers
- double handles zero and negatives
- doubled contains [2, 4, 6]
Take this with you
A reusable function describes a relationship between inputs and outputs.