A function is a named block of code that you can run whenever you need it. You have been using one all along: console.log. Now you will write your own.
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Noor");
greet("Luca");
function greet(name) { … }defines the function. Nothing runs yet.nameis a parameter: a variable that receives a value each time the function is used.greet("Noor")calls the function."Noor"is the argument that goes intoname.
A function can have several parameters, separated by commas, or none at all.
Returning a value
Most functions calculate something and hand it back with return:
function area(width, height) {
return width * height;
}
const room = area(4, 5);
console.log(room); // 20
console.log(area(2, 3)); // 6
A call to the function is replaced by the value it returns, so you can store it, print it, or use it in a bigger calculation.
return also ends the function immediately. Lines after it do not run.
Printing and returning are different. console.log shows a value to a person. return gives a value back to the code that called the function. A function that only prints cannot be used in a calculation.
Why functions matter
Functions let you write a piece of logic once and use it everywhere. If it needs to change, you change it in one place. They also give a name to an idea, which makes programs easier to read.
Your Task
- Write a function
doublethat takes one number and returns that number times 2. - Write a function
fullNamethat takes a first name and a last name and returns them joined with a space between. - Print the result of
double(21).
doubleis a function that returns twice its inputfullNamereturns both names with a space between- Both functions use
return 42is printed by callingdouble(21)