Functions
Give a piece of code a name, hand it values, and get a result back.
Your JavaScript code runs inside your browser tab. Nothing to install.
Defining and calling a function
A function is a named block of code. Defining it does not run it. It runs when you call it, by writing its name followed by round brackets.
A function can be called as many times as you like. This saves writing the same lines again.
function greet() {
console.log("Welcome");
}
greet();
greet();Giving a function values
A parameter is a variable that receives a value each time the function is called. Parameters are listed in the brackets of the definition.
The values you pass when calling are matched to the parameters in order.
function greet(name) {
console.log("Welcome, " + name);
}
greet("Asha");
greet("Bilal");Your turn: a function with a parameter
Write a function and call it twice.
Practice task
Write a function `showDouble` that takes a number and prints twice that number. Call it with 4, then with 10.
Your answer is run and checked in the lesson. Create a free account to try it.
Getting a result back
return hands a value back to the place where the function was called, and ends the function.
A function that returns a value can be used inside a calculation, stored in a variable, or passed straight to console.log.
Printing shows a value on the screen. Returning gives it back to the program. They are different things.
function area(width, height) {
return width * height;
}
let room = area(4, 5);
console.log(room);
console.log(area(2, 3) + 1);Your turn: return a value
This function must give its answer back, not print it.
Practice task
Write a function `larger` that takes two numbers and returns the bigger one. Print larger(7, 3) and then larger(2, 9).
Your answer is run and checked in the lesson. Create a free account to try it.