FAQ: Functions - Return

This community-built FAQ covers the “Return” exercise from the lesson “Functions”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise Return

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

4 posts were split to a new topic: Why is return necessary?

12 posts were split to a new topic: Why do I need to use return?

3 posts were split to a new topic: Am I missing something with this code?

A post was split to a new topic: Why doesn’t this run in google console?

3 posts were split to a new topic: What is the point of this function?

I dont really understand why we need to use return in this case, but not in any of the previous examples

Is it because something is being calculated, and we have to retrieve the answer?

1 Like

As in, expect some result to echo back from a function call that can be useful in future computations.

Hello, I can not seem to understand the usage of the return keyword inside of a function.
Here is an example that I do not understand the console output. I would really appreciate if someone could explain these lines of code step by step.

function callMe(name) {
	return name;
}
let name = callMe("Marios");
console.log(name);

// SEPERATE LINE

function buy(item) {
	return item;
}
buy("Onions");

In maths we first learn about the identity function…

f(x) = x

In code, we would write this much like your examples…

function f(x) {
    return x;
}

Not a lot happening here, but what happens if we wish to transform x?

f(x) = 2x + x

y = f(x)

y = 2x + x
function f(x) {
    return 2 * x + x;
}
y = f(5)
console.log(y)
// 15

return is the path back to the caller, meaning we can pass a value back. In the above the return value is assigned to y.

If our function does not do anything, then a call to the function will result in nothing. Your second example calls the function but doesn’t use or assign the return value, so nothing happens that we can tell.

In maths we are focused on Number, whereas in computing we are focused on Data. A function can process any type of data, numeric, string, data structures, etc.

function doubleLastAndAppend(list) {
    list.push(list.slice(-1) * 2);
    return list;
}

a = doubleLastAndAppend([1])
<- [1, 2]
a = doubleLastAndAppend(a)
<- [1, 2, 4]

Notice that a becomes the return value. We started by passing in a simple array, found the last element, doubled its value and appended it to the array. The return value is then assigned back onto a.

You should be familiar with arrays, at this point, but may not have used push or slice methods. They should come up, if they haven’t already, but it can’t hurt to look these two methods up on MDN.

Array.prototype.push()

Array.prototype.slice()
3 Likes

Until this point it was pretty understandable, but this return…, so confusing :frowning:

2 Likes

Hello, @tuzso.

I would suggest that you experiment on your own with what return does. Just play around with it until things become more clear. Start with simple examples, and steadily increase the complexity as you go. Make sure you always understand what is happening before moving on. Feel free to ask questions along the way. Here is some sample code you may feel free to start with if you like:

function doSomething(param) {
  console.log(`I don't feel like doing something with or without your ${param}.`) //this will print every time the function is called
}  

doSomething() // function is called
console.log(doSomething()) // the function is called, and the implicit return value, 'undefined' is also printed

doSomething('pizza') // function is called, and the message is printed
console.log(doSomething('blinker fluid')) // the function is called, and the implicit return value, 'undefined' is also printed

function doSomethingElse(param1, param2) {
  return param1 == param2 //will return 'true' if they are equal, otherwise, 'false'
}

const myBool = doSomethingElse('pizza', 'hamburger') //calls function and assigns return value to myBool
console.log(myBool) //prints the value assigned to myBool, 'false'

console.log(doSomethingElse(11, 'eleven')) //calls funtion, and the return value is printed then lost since not assigned to any variable
3 Likes

In the previous exercises, we typed in the “const” in the body of the function. How come in this exercise the const is outside? Thank you!

1 Like

One will find that exercises vary quite a bit. Each lesson and exercise may be singular in nature, and the next something entirely different though related to the subject of the unit/module. It’s actually quite abrupt but quite necessary owing to the immediate need of exposing as many of the language concepts as possible in a short time frame.

That preamble aside, your question is a good one. Recall that functions have their own scope, inaccessible from outside, even of parent functions. The only problem is that if we do not define scope then JS has no choice but to define variables in global scope, root scope to be precise. They become properties of the window object where they are vulnerable to collisions where they may be overwritten or nullified.

To prevent these sorts of potential calamities we define scope inside the block. This keeps variables from polluting global scope and protects them from outside influences.

const pi = Math.PI;
let i = 0

Both of the above define scope, block scope, as we refer to it.

Rather than continue, may I leave you to research that term? It will open avenues of understanding that more than cover this question.

Hello,

I don’t understand why const is necessary in this exercise:

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

It seems like an unnecessary addition to the code when the following works as well:

function monitorCount(rows, columns) {return rows * columns}
console.log(monitorCount(5,4))

What am I missing?

7 Likes

Hello, @data1411871858.

Welcome to the forums.

If the only goal here is to print the value to the console, then you’re absolutely correct. We don’t need to first assign the return value to a variable. If we later wanted to do something with that value, however, having it assigned to the variable is quite useful. The exercises may not always be great ‘real world’ examples, but they are teaching us things that are possible whether or not they are necessary.

It is great though to see you thinking this way. Do I really need that in my code? That type of thinking, and refactoring code to make it more efficient are great qualities in a coder. :slightly_smiling_face:

7 Likes

This is helpful, thank you!

1 Like

function testTentrary (rows, columns) {
rows < 0 || columns < 0 ? return ‘You need positive integers to calculate area!’: return rows * columns;
};
Instead of conditional i try to use tenantry for this example, can not understand why is not working…

A ternary expression will work here. You just need to alter the order a little:

function testTernary (rows, columns) {
 return rows < 0 || columns < 0 ? 'You need positive integers to calculate area!': rows * columns;
}

console.log(testTernary(-5, 5))
console.log(testTernary(5, 5))

Output:

You need positive integers to calculate area!
25

1 Like

Thanks, it’s working ))
Got it,just need to add return in front, because i add for else if and else and it crashes again.

function testTernary (rows, columns) {
return rows < 0 || columns < 0 ? ‘You need positive integers to calculate area!’: return rows === 0 || columns === 0 ? ‘Zeroooo’ : return rows * columns;
}