Why do I need to use `return`?

I don’t see the point of using ‘return’?

Why not just have a console.log statement in the function body and call the function when needed with whatever arguments are needed?

This example also seems like variables for the sake of variables.

What if we wanted to use the returned value in the future? By using return, we can store the returned value in a variable, use it in another function, console.log() it, etc. For example, what if we wanted to calculate the area of a rectangle? And then, what if we wanted to use this value to compute how many rectangles are needed to fill a certain area? Example code follows. See how return can be useful?

function areaRectangle(length, width) {
  return length * width;
}
const rectangleArea1 = areaRectangle(2, 6);
console.log(rectangleArea1); // logs 12

function rectanglesToFill(areaToFill, rectangleArea) {
  return areaToFill / rectangleArea;
}
const rectangle1sToFill = rectanglesToFill(96, rectangleArea1);
console.log(rectangle1sToFill); // logs 8

Alternatively, you could call the areaRectangle() function within the rectanglesToFill() function (rather than storing the value returned from areaRectangle() and passing it to rectanglesToFill(), we could simply pass in a call to areaRectangle() for the area parameter in rectanglesToFill()).

Yeah got confused with the example also. They declared the constant variable after the function. we know that its not logical for us to easily understand.

Thank you for clarification.

1 Like