 # How exactly does return work?

Hi. I’m learning about return in the functions lesson. A few things confuse me though. I’d be grateful if someone could help.

``````function calculateArea(width, height) {
const area = width * height;
return area;
}
``````

First of all, why didn’t the example code just use `rectangleArea(5, 7)` instead of `console.log(rectangleArea(5, 7)`? It just seems like extra work. Not to mention that it comes out with `undefined`.

``````function CalculateArea(width, height) {
const area = width * height ;
return area;
}
``````

Why is `return area;` used here instead of just the normal `console.log(area);`? I get it stops the following code from running, but does it stop EVERYTHING within it’s block from running? Even if it’s in an if statement such as

``````function rectangleArea(width, height) {
if (width < 0 || height < 0) {
return 'You need positive integers to calculate area!';
}
return width * height;
}
``````

Sorry for the long post. I just want to fully understand what’s going on before I go forward. Thanks

1 Like

Hi there.

We see many of the learners here get confused when it comes to the difference between logging output to the terminal, and returning output from functions.

I can summarise the difference like this:

`console.log()` writes something to the terminal, providing you with a view into your program at that point. It is useful to you, as the programmer, to see what is happening - like the glass in a washing machine door - but it’s of no use to your program.

`return` is the keyword which hands data from your function back into your program. It doesn’t tell you, the programmer, anything but it is the means by which your function communicates with the rest of your program.

As an example, let’s consider a trivial function to calculate the area of a triangle:

``````function triangleArea(base, height) {
let area = 0.5 * (base * height);
}
``````

If we use `console.log()` inside this function, we can see the result of the calculation…

``````function triangleArea(base, height) {
let area = 0.5 * (base * height);
console.log(`Triangle area is: \${area}`);
}

triangleArea(2,5); // output: "Triangle area is: 5
``````

…but we can’t do anything useful with it:

``````function triangleArea(base, height) {
let area = 0.5 * (base * height);
console.log(`Triangle area is: \${area}`);
}

let myTriangleArea = triangleArea(2,5);
console.log(myTriangleArea); // output: undefined
``````

Generally, when we are creating a function it is because we want to create a re-usable block of code. This may, as in this example, take the form of a calculation which takes certain variables and provides a result. Using `console.log()` allows us, the programmer, to see the result… but we can’t use it within the program.

`return` is the mechanism that lets us get that result from our function, and use it elsewhere:

``````function triangleArea(base, height) {
let area = 0.5 * (base * height);
return area;
}

let myTriangleArea = triangleArea(2,5);
console.log(`Area of a triangle with base 2 and height 5 is \${myTriangleArea}.`); //output: "Area of a triangle with base 2 and height 5 is 5."
``````

It does not matter where in the function your program encounters the `return` keyword; as soon as it does, the function will terminate and whatever statement follows the `return` is returned.

If we simply have `return`, then you get the default return value back which is `undefined`. If we had, say, `return "These aren't the droids you're looking for."` then our return value is a string.

Hopefully that has helped.

To summarise:

`console.log()` is there to provide output to you, the programmer/user.

`return` is there to provide output from your functions to the rest of your program.

Let us know if you’re still unclear. 5 Likes

Although @thepitycoder answer is excellent, I would like to add one or two small things

Why do we use height to calculate an area? Shouldn’t that be `length`?

first, in this code sample:

`````` function calculateArea(width, height) {
const area = width * height;
return area;
}
``````

`area` is a local variable. There is no way we can access this variable outside the function.

which can be impractical. What if we now want to calculate the dimension (area * height), so we make another function where we want to do:

``````function calculatedimension(width, length, height) {
calculateArea(width, length) * height;
}
``````

Because we don’t want to repeat the logic we already have

this is where `return` comes into play and start to shine. Not only can we pass information to a function (`arguments`) we can also receive data back (`return`)

allowing you to write code into small, testable and re-usable components.

6 Likes

Thank you for your reply. This clears it up a lot! I still have one or two questions if that’s alright. When `return area` is used, does this mean that area’s value can be used elsewhere outside of it’s block by calling it’s function? Also, when a string is used after a return, how and where would it be used? (You may have seen I deleted a reply. It’s because I didn’t fully understand the answer so I rephrased my questions)

2 Likes

`return` passes whatever comes after it out of the function and back to the caller.

You can either capture the return value in a variable, like I did, for use elsewhere; or, you can plug the call to the function in directly as @stetim94 did in the `calculatedimension()` function example.

Either approach allows you to use the product of the function, handed back by `return`, elsewhere in your program.

This is the good thing about programming.

It’s up to you to determine what the functions you write should return. Generally, your function exists to serve a single, specific purpose; and that purpose will have a logical product. If you’re performing a calculation, for example, then the logical return type would be a number. If your function is performing a test, then perhaps a boolean return type (`true`/`false`) would make sense.

It’s equally up to you to decide how the output of the function is used.

3 Likes

Thanks. I get the first bit now I’m still just a tiny bit confused on the second bit. In your example, you used area and area was then used in a console.log(). If a string is after the return, then what is the return actually taking out of the function? If it’s something like `return 'Hello there'` then wouldn’t everything else in the function be void since it never comes out of the function?

2 Likes

Thank you for your reply. I never thought of it like that. Thanks for clearing it up 2 Likes

The `return` sends whatever comes after it, so `return 'hello there'` returns the string ‘hello there’. You could use this in a number of ways, such as giving your user information about the program, or have an action done with the string later in the program.

As @thepitycoder said:

Perhaps you may find yourself in a position were you need to return a string, as part of the program later depends on it.

After the `return` is executed than the function terminates and any other code in it is not executed. This is were the logic comes in to play.

For example, in your first post:

``````function rectangleArea(width, height) {
if (width < 0 || height < 0) {
return 'You need positive integers to calculate area!';
}
return width * height;
}
``````

There are two return statements, the first one returning a string, and the second returning the value of `width * height`. If the condition of the `if` block evaluates to `true` than the first return is executed, and a string is returned. This will end the function so that an inaccurate value based on the function being given negative numbers won’t be returned.

In this case the string behaves similar to an error message, but suppose you have a function that acts as a word censor, than the returned string will simply be the result of calling the function.

1 Like

Thanks for clearing this up!

2 Likes

And just to toss this in,

``````return expression
``````

where `expression` is optional (in other words we want something other than `undefined` to be returned).

We know that anything that can be resolved or evaluated to a value, is an expression. All expressions are values.

``````a + b

x.toLowerCase()

array.indexOf(value)

"The rain in Spain falls mainly in the plains."
``````

Those are all expressions.

``````a > b

a && b

a ** b
``````

Also expressions.

``````if (a > b) {
return true
} else {
return false
}
``````

Not an expression, but a statement. However, it can be written in expression form in the return statement…

``````return a > b
``````

Lastly, when returning a multi-line expression such as a plain object or array, the first character (`{` or `[`) must be on the same line as the return keyword.

``````return [
'apples',
'oranges',
'bananas'
]

return {
fruit: 'apple',
vegetable: 'carrot',
nut: 'pecan'
}``````
2 Likes