Hi! Good queston, I’ll try to explain.
Let’s compare two functions:
The first
function rectangleArea(width, height) {
return width * height
}
console.log(rectangleArea(5, 7))
Output:
35
And the second
let width;
let height;
function rectangleArea(width, height) {
let area = width * height
console.log(area)
}
rectangleArea(5, 7)
Output:
35
Exactly the same result, you can call functions using both variants, but what’s the difference?
console.log() just logs out information in console, you can’t use it in your further work.
That’s why we got undefined with the second function:
let area = rectangleArea(5, 7);
console.log(area);
Output:
undefined
But if you do the same thing with the first function, you will get 35.
let area = rectangleArea(5, 7);
console.log(area);
Output:
35
And you will be able to use variable area
with the value 35
in further calculations.
console.log(area * 2)
Output:
70
So, if you want just check the value (e.g. for debugging), use console.log(), and if you want to store the value and work with it, use return.
And here is the article with more detailed explanation: