FAQ: Functions - Return

What’s the practical use difference between declaring a variable inside the function and returning it vs returning the value and declaring the variable outside via calling the function?

Variables declared within the function are intermediate, and perhaps only serve to give names to data objects for readability.

const addab = (a, b) => a + b;

c = addab(6, 7)

console.log(c)    //  13

Above we return the value without creating any intermediate variable. We could have stretched it out, though…

const addab = (a, b) => {
    const c = a + b;
    return c
}

I fixed it but I don’t get why this is wrong…

function monitorCount(rows, columns){
numberOfMonitors = rows * columns; 
return numberOfMonitors;
const numOfMonitors = monitorCount(5,4);
}
console.log(numOfMonitors)

Consider what return does. You have a line of code inside your monitorCount function that is after the return. That line of code is unreachable. It will never be executed, so when you try to log numOfMonitors outside the function, you get an error because numOfMonitors has not been defined.

Also, since the only call to your monitorCount function is inside the function itself, the function is never called.

I came up with this solution to the exercise but received an error message:

function monitorCount(rows, columns) {
const numOfMonitors = monitorCount(5, 4);
console.log(numofMonitors);
return rows * columns;
}

Why did I receive an error message?
I was concerned that once the code block hit return, nothing else would be executed so I wanted the instructions to appear before return.

The solution has the same lines of code as my solution but after return. Why would it execute the rest of the code once it has encountered break?

Please refer to How do I format code in my posts? for future posts, so your code looks like it did when you wrote it. The two lines of code you are likely referring to are these:

const numOfMonitors = monitorCount(5, 4);
console.log(numofMonitors);

They should not be inside the function at all. The solution probably looks like this:

function monitorCount(rows, columns) {
  return rows * columns; //This line sends the value assigned to rows (5) multiplied by the value assigned to columns (4) back to the caller (the line of code that called the function), so 20 is returned
};

const numOfMonitors = monitorCount(5, 4); //This line calls the function, and passes 5 which will be assigned to the rows parameter, and 4 which will be assigned to the columns parameter. The return value will be assigned to numOfMonitors
console.log(numOfMonitors);

What you received was probably a message from the SCT (Submission Correctness Test) because your code doesn’t call the function or print anything to the console.

Thank you for your guidance on how to format code in my posts and I will refer to it for future questions.

The example in the lesson included return in between the curly brackets so I did likewise. I thought when the instruction hit return, everything stopped after that. Why doesn’t my solution log anything?

In your code the only call to the function is inside the function itself. You need that and the console.log statement to be outside of the function like the solution shows. Functions are not executed until they are called. When they finish either from executing a return statement or simply reaching the end of their code block (the code between the curly braces), control is passed back to the caller, and execution continues from there.

1 Like

Why do we use “Return” in exercise 6, but in exercise 4 " Parameters and Arguments" we did not need to use “Return” in order to pass back information from the function call and log the name “Cole”? Is console.log the only exception within the curly brackets?

I don’t really understand return. Can someone please explain its use and provide an example?

A function has two channels that permit the movement of data into and out of its body. The parameter, input, and the return, output. The parameter takes data from the caller, the argument, and sends data back to the caller, the return value. When a function has no literal return, it sends back a default value, None.

function (parameter) {
    // function body
    // do something with parameter(s)
    return resulting_value
}

Let’s consider a function that will add two input values and return the sum…

function add (a, b) {
    return a + b
}

console.log(add(6, 7))   //  13

The return value of a function can be any object, a number value, a string value, a boolean value, an array, object or set, or even a function (also an object).

What is important to understand is that inputs go from caller scope to function scope, return values go from function scope back to caller scope. We can call any function that is accessible to that scope, and the return always goes back to the same scope where the call came from.

1 Like

So, in short, return statements are used to send data back to the caller. We can then use this data in many ways, E.g. we can assign it to a variable, we can log it to the console, etc.

Parameters, on the other hand, are used to receive data (input) from the caller and use it to perform a certain task

Do correct me if i’m wrong

3 Likes

Hi,

I’m confused about something about this example in relation to the previous modules and exercise.

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

My questions are:

  1. Why would we put the var let area when it doesn’t match in the console? We’re calling rectangleArea and not just area so how would the console recognise the value anyway?

Going back to this exercise:

function sayThanks(name) {
  console.log('Thank you for your purchase ' + name + '! We appreciate your business.');
}
sayThanks('Cole');

Why wouldn’t the same principle work for the rectangleArea when we call the function outside of the box with rectangleArea(5, 7) ? Why would it still show as undefined even though I called the values in the parameter?

Many thanks in advance!

That is an intermediate step (compute area). We still need to return the value to the caller.

return area

For question 2, console.log() is not the same a return. They are not interchangeable. The function still has a return, undefined, which is the default, and in this case also what console.log() returns.

function foo(a, b) {
    return a + b
}

console.log(foo(5, 37))    //  42

I appreciate this thoughtful answer, but I still don’t understand why const appears outside of the block?

When const is outside of the block, it applies in the outer scope, as well as in the block.

1 Like

Thank you! Seems so obvious now but just wasn’t clicking at the time.

1 Like

@tagace54183 Hopefully the following posts in this thread answered your questions!

:sparkles: What you said about using return to pass back information is exactly right!

Let’s take a look at the examples used in these exercises so we can understand them better:

// exercise 6 function monitorCount(rows, columns) { return rows * columns; } const numOfMonitors = monitorCount(5, 4); console.log(numOfMonitors); // exercise 4 function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'eggs') { console.log(`Remember to buy ${item1}`); console.log(`Remember to buy ${item2}`); console.log(`Remember to buy ${item3}`); } makeShoppingList();

Notice how exercise 6 has a variable, numOfMonitors whereas exercise 4 has no variables. This is actually the key difference, and why we use return; in exercise 4, there is no way for us to retrieve what has been printed to the console without rewriting the code, however, in exercise 6, we can use the value of rows * columns again, however many times we want, because return allowed us to save that value.

I hope this helped! :sparkles:

Isn’t console.log() supossed to be inside the function body?

@nobitanobii Welcome to the forums!

I assume you are referring to exercise 6, which by the way, good question >:D I suggest playing around with the code, and putting console.log inside the function, so we have

// doesn't output to console function monitorCount(rows, columns) { return rows * columns; console.log(numOfMonitors); } const numOfMonitors = monitorCount(5, 4); // outputs to console // function monitorCount(rows, columns) { // return rows * columns; // } // const numOfMonitors = monitorCount(5, 4); // console.log(numOfMonitors);

Putting console.log inside the function does run, but the result does not show up in the console. This is because the computer performs what is in the function, and stores the answer in a variable, which is not visible to the user. In order for us to see the code, we have to output the variable (numOfMonitors) to the console outside the function.

Hope this made more sense!