How does return work?

thanks for the great explanations about arrays, it helped a lot :heart:
now I have a new problem: the return!
I cant understand this! :angry:
please explain, I am sooooooo stuck!

Well, return is mostly used for functions (in codecombat at least). What it does is “return” or “output” a value. If I ran this code:

def add(a, b):
    sum = a + b
    return sum

a = 5
b = 9
a_and_b = add(a, b)
hero.say(a_and_b)
# >-- output: 14

What the function is doing is first making a variable sum, and setting it to a + b. Then it’s returning that value. In this case it’s putting that value into the variable a_and_b. You can’t just run a function that returns a value by itself, because it needs to return it’s value into something.
You could also skip round the variable entirely:

a = 5
b = 9
hero.say(add(a, b))
# >-- output: 14

The function will work as long as you’re doing something with the value it’s returning.
I hope that helps you understand,
Danny

1 Like

wow thanks(even thought i’m not foxfire) i didn’t even know that and i’m up to glacier(almost finished everything)

hello @Deadpool198, you cleared a lot to me, but yet I still have another problem: how do you use return in a condition?
for example:

function gold () {
if (hero.gold > 200) {
return rich
}
else {
return poor
}
}

(this is just some code I used as a sample)
now I want to know if I’m rich or poor.
how can I do it?
with many thanks,
foxfire :fire:

You need to have the semicolon ; and quotes " when returning a string. So to fix that code, you’ll get this:

function gold () {
    if (hero.gold > 200) {
        return "rich";
    }
    else {
        return "poor";
    }
}

Using the above code, you can use something like:

if (gold() == "rich"){
    self.say("I'm rich!");
}
else{
    self.say("I'm poor.");
}

Return basically returns whatever value in the return statement. You can return booleans, numbers, strings, etc.

2 Likes

thanks for the explanation! :heart_eyes: