JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge, Part 2

When do I call return?

In this video he said write a function print(message)

but why doesnt he return?

Why other functions like randomColor return color and function randomNumber?

1 Answer

Justin Cantley
Justin Cantley
18,048 Points

You would want to return from a function if you want to call the function in order to assign the return value to a variable. For instance:

function add(x, y) {
    let sum = x + y;
    return sum;

let result = add(4, 5); //by calling the add() function here it will return 9 and assign it to result

In the case of calling the print() method, you would not need to return the value, because the print() method performs an action (document.write()) instead of returning a value.

:smile: ty

Justin Cantley
Justin Cantley
18,048 Points

No problem. I hope this helped. The following links have some helpful documentation if you want to know more.
W3 Schools