Lesson ยท 12 min
Functions
A recipe with a name
A function is a block of code with a name. You write it once, and you can use it as many times as you like. Programmers call a function by writing its name with parentheses.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
console.log(add(10, 5)); // 15
The parts of a function:
functionstarts the definition.addis the name.aandbare parameters. They are names for the values that the function receives.- The code between the braces is the body.
returnsends a value back to the code that called the function. The function stops atreturn.
The values that you give to a function when you call it, such as 2 and 3, are arguments.
Return and print are different
console.log shows a value to a person. return gives a value back to the program. A function that only prints gives nothing back, so you cannot use its result in a calculation. Prefer return when a function calculates something.
Arrow functions
JavaScript has a shorter way to write a function. It uses =>.
const add = (a, b) => a + b;
When the body is one expression, the arrow function returns its value, and you do not write return.
Your turn
Write five functions. The checker calls each function with several values. It does not read your code to find the answer, so write the general rule, not a single answer.
Tasks
5 to do
Task 1, not checked yet. Write a function named
doublethat takes a numbernand returnsnmultiplied by2.Task 2, not checked yet. Write a function named
greetthat takes anameand returns the textHello,followed by the name and an exclamation mark.greet('Sam')returns'Hello, Sam!'. Use a template string.Task 3, not checked yet. Write a function named
averagethat takes two numbers,aandb, and returns their average.Task 4, not checked yet. Write a function named
isEventhat takes a numbern. It returnstruewhennis even andfalsewhen it is odd.Task 5, not checked yet. Make a constant named
squarethat holds an arrow function. It takesnand returnsnmultiplied by itself.
Task 1 of 5
Write a function named double that takes a number n and returns n multiplied by 2.