JavaScript

Lesson 8 of 11

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:

  • function starts the definition.
  • add is the name.
  • a and b are parameters. They are names for the values that the function receives.
  • The code between the braces is the body.
  • return sends a value back to the code that called the function. The function stops at return.

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

  1. Task 1, not checked yet. Write a function named double that takes a number n and returns n multiplied by 2.

  2. Task 2, not checked yet. Write a function named greet that takes a name and returns the text Hello, followed by the name and an exclamation mark. greet('Sam') returns 'Hello, Sam!'. Use a template string.

  3. Task 3, not checked yet. Write a function named average that takes two numbers, a and b, and returns their average.

  4. Task 4, not checked yet. Write a function named isEven that takes a number n. It returns true when n is even and false when it is odd.

  5. Task 5, not checked yet. Make a constant named square that holds an arrow function. It takes n and returns n multiplied by itself.

Task 1 of 5

Write a function named double that takes a number n and returns n multiplied by 2.

All tasks

main.js

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.