Why do I need to use `return`?

My take on this exercise, is that there are two alternatives that result in the same answer, as follows:

1. The exercise asks for:

function monitorCount(rows, columns) {
return rows * columns;
}
const numOfMonitors = monitorCount(5, 4);
console.log(numOfMonitors);

2. Whereas, the example used in the initial explanation would suggest:

function numOfMonitors(rows, columns) {
const monitorCount = rows * columns;
return monitorCount;
}
console.log(numOfMonitors(5, 4));

I actually found it a positive thing that this confused me a bit at first, as it made me think harder about how the different sections of code were interacting.

I can see that both sets of code give the same final result, but that the key difference seems to be whether the variable is defined within the function (alternative 2) or outside of it (alternative 1).

For the moment, I can see this theoretical difference, but I can’t yet grasp whether there are also any practical reasons why defining the variable within the function may sometimes be preferable, and sometimes not. This is something that will no doubt become clearer as I learn, practice and experiment more; but I’m also interested to know if anyone has any thoughts on this, or could guide me in the right direction… :thinking:

67 Likes