Skip to the content

Project: work out your average

JavaScript · Unit 1: First steps

A function is code with a name that you can use whenever you want.

You create it with function, it receives data inside parentheses and hands over its result with return.

What goes inside goes between curly braces.

function double(n) {
  return n * 2;
}

console.log(double(4));

Prints

8

A function can receive several pieces of data, separated by commas.

Inside, each one is used like any other variable.

function add(a, b) {
  return a + b;
}

console.log(add(3, 4));

Prints

7

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Put the lines in order

    Order the lines to create the function triple and use it with 5.

  2. 2. Multiple choice

    Inside a function, how are return and console.log() different?

  3. 3. Write the code

    Write the function area(side) that gives back the area of a square, which is side times side. For example, area(5) gives 25.

    function area(side) {
      // Write your return here
    }
  4. 4. Complete the code

    Fill in the function so it hands over the subtraction of the two numbers.

    function subtract(a, b) {
      return ___;
    }
  5. 5. Write the code

    Write the function average(a, b, c) that gives back the average of three grades. For example, average(80, 90, 100) gives 90.

    function average(a, b, c) {
      // Write your return here
    }
Do this lesson

It opens in your browser. It is free and you do not need an account to start.

See all lessons →