JavaScript · Unit 2: Decisions, functions and loops · Lesson 2 of 6
Functions and return
A function is a named piece of code you can reuse.
Opens this lesson in Code Academy. Lessons open one after another, and each unit opens when you pass the checkpoint quiz before it (you can take a checkpoint early to skip ahead). If this lesson is not open yet, the button shows you its unit on your map.
The idea
A function is a named piece of code you can reuse. Define it once, then call it as often as you like: greet().
Parameters are the inputs listed in the parentheses. The values you pass in when you call it are the arguments.
return sends a value back to the code that called the function, and ends the function. A function without return gives back undefined.
Worked example
JavaScript
function area(width, height) {
return width * height;
}
console.log(area(3, 4));
console.log(area(10, 2));
It prints
12
20
Key terms
- Function
- A named, reusable block of code that takes parameters and can return a value.
- return
- Hands a value back to the caller and ends the function. Without it, a call gives undefined.
Practise it in Code Academy
It has 4 exercises (multiple choice, predict the output, fix the broken code and write code from a prompt) and takes about 8 minutes. Every answer is checked as you go, and feedback names the exact mistake. Hints and the solution are there if you get stuck.
Every lesson is free: no ads, no lives and no paywall.