Why do we need to use 'return', as opposed to just calling the function like we learned previously?

hey all, beginner coder here.

in the function section, we learned about the ‘return’ keyword. this was the example:
function rectangleArea(width, height) {
let area = width * height;
}
console.log(rectangleArea(5, 7)) // Prints undefined

above, we learned that this returns undefined since we didn’t capture this. this is where we use the return key.

my question is why we can’t use the normal way we call functions to get the desired outcome (ie. rectangleArea(width, height)?

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:

4 Likes

The ‘return’ statement in programming serves a crucial purpose by allowing a function to produce a value or result that can be utilized elsewhere in the code. Unlike just calling a function, which executes its code without providing a way to capture the result, ‘return’ enables the function to pass data back to the caller. This facilitates better modularization and reusability in code. If your stack in any code, you can hire Java developers from any IT staffing agency; they may help you complete your current project.

Here’s an example in Python:

def add_numbers(a, b):
    result = a + b
    return result

# Calling the function and capturing the result
sum_result = add_numbers(3, 5)

# Now, 'sum_result' holds the value 8, allowing further use in the code
print(sum_result)

In this example, without the ‘return’ statement, the function wouldn’t provide a way to obtain the sum of two numbers for use elsewhere in the program.