Home 07: Functions - return
Content
Cancel

07: Functions - return

Functions can also return values. You don’t need that to draw your emoji, but sometimes it can be very useful, and you will use it later during the course.

To start, we will have a look at a simple function that takes two values and multiplies them:

1
2
3
4
5
6
function multiply(a, b) {
  let result = a * b;
  return result;
}

console.log(multiply(14, 3));

This code will output the following in your console:

1
42

As you can see, the function multiply takes two arguments a, and b. Next a variable is created inside the function called result. The value for this variable is the multiplication of a and b. In the next line, we return the value of result. You can see that return is a keyword. If we now call or execute the function, it will return the value of result to us. Try it out yourself.

You can also store the result in a variable and use it for some other calculations, for example.

To multiply two values with each other, that is a lot of code, but you can use this to calculate more complex values as you will see later in the course.

Another simple example would be a greeting function, that will always add the correct greeting to a name:

1
2
3
4
5
function greeting(name) {
  return "Hello " + name;
}

console.log(greeting("Garrit"));

This code will output the following in your console:

1
Hello Garrit

Exit a function early

The return statement is often used to exit a function early. Exit means, we are stopping the function from executing. All the code behind the return keyword will not be executed. In one of the next chapters you will learn about conditional statements and combined with the return keyword, you can exit a function if a certain condition is not met.

This post is licensed under CC BY 4.0 by the author.