# return statement in JavaScript

Suppose we have a function that prints the square of the passed number to the console:

`function func(num) { console.log(num ** 2); }`

Suppose we do not want to display the value to the console, but write it to some variable, like this:

`let res = func(3); // now there is 9 in the res variable`

To do this, JavaScript has a special instruction `return`, which allows you to specify the value that the function returns. The word "returns" means the value that will be written to the variable if the called function is assigned to it.

So, let's rewrite our function so that it does not print the result to the console, but returns it to a variable:

`function func(num) { return num ** 2; }`

Let's call our function now, writing its response to a variable:

`let res = func(3); // 9 will be written to the variable`

After the data is written to a variable, they can, for example, be output to the console:

`let res = func(3); console.log(res); // shows 9`

Or you can first somehow change this data, and then print it to the console:

`let res = func(3); res = res + 1; console.log(res); // shows 10`

You can immediately perform some actions with the result of the function before writing to a variable:

`let res = func(3) + 1; console.log(res); // shows 10`

Or you can not write the result to a variable, but immediately print it to the console:

`console.log(func(3)); // shows 9`

You can invoke a function in one expression with different parameters:

`let res = func(2) + func(3); console.log(res); // shows 13`

Make a function that takes a number as a parameter and returns the cube of that number. Use this function to find the cube of the number `3` and store it in the variable `res`.

Make such a function that takes a number as a parameter and returns the square root of that number. Use this function to find the root of `3`, then find the root of `4`. Sum the results and print them to the console.

←→
↑
en ru