Return Function Lesson

Below is an example from the ‘Return’ lesson in ‘Functions’. I understand how returning width * height would work but how would ‘let area = width * height’ be expected to print to the console when calling rectangleArea(5, 7) as it’s not associated (as far as I can see) with the variable ‘area’? I know it prints as undefined regardless but I just don’t understand the relevance of this example as it stands.

function rectangleArea(width, height) {
let area = width * height
console.log(rectangleArea(5, 7)) // Prints undefined

In the code example, we defined our function to calculate the area of a width and height parameter. Then rectangleArea() is invoked with the arguments 5 and 7 . But when we went to print the results we got undefined . Did we write our function wrong? No! In fact, the function worked fine, and the computer did calculate the area as 35 , but we didn’t capture it. So how can we do that? With the keyword return !

If you mention a lesson, can you also include the lesson/exercise url? That would be massive help

As i currently read your post, the lesson deliberate has an “incomplete” example, so it can demonstrate the use of return.


Did you also read the next bit:


that is so crucial to grasp the example you mentioned

I did read that and am starting to get a better understanding, I’m very new to programming and have gone over all the lessons numerous times in order to get a better understanding of why and how things work the way they do. I know this is just a sample to get a point/idea across but still don’t understand why the let area = width * height was included since it will print undefined regardless of whether this line is included or not… is it to show that return should be used instead of assigning the calculation to a variable? Maybe I’m just overthinking things.

that is also possible:

return width * height

but with variable is also possible, its just an extra step:

let area = width * height
return area

but as your function grows, having multiple steps in the function before returning a value might be useful :slight_smile:

Ah, I see it now, guess you can teach an old dog new tricks ( just turned 51 :wink: I appreciate you taking the time to go over and explain this to me.

1 Like