What does `return` do?

Can someone please tell me what this {…return sandwich} in function mean?

return sends whatever follows back to the line of code that invoked the function which programmers refer to as the ‘caller’. In this case the value stored in the variable sandwich is returned. This is a very rudimentary example of a function to show the basic structure in a generic programming language.
Consider this:

function makeSandwich(topping1, topping2) {
  return 'bread, ' + topping1 + ', ' + topping2 + ', ' + 'bread';

console.log(makeSandwich('ham', 'cheese')); //This line of code is the caller when executed
console.log(makeSandwich('peanut butter', 'jelly')); //Same for this line
console.log(makeSandwich('turkey', 'provolone')); //Also this line


bread, ham, cheese, bread
bread, peanut butter, jelly, bread
bread, turkey, provolone, bread

The code above is JavaScript, and you can see that by using a function we can repeat actions as often as we like by invoking the function. The console.log() method is JavaScript’s way of printing output to the console, so we can see it. Don’t get too hung up on understanding everything just yet. This will all make a lot more sense as you progress on your learning to code journey. Happy Coding!


Thank you for your reply

1 Like

I’m on .5 Putting It All Together. I am told to change ‘burger patty’ and ‘pickles’ to ‘peanut butter’ and ‘jelly’. I set burger patty = peanut butter, and pickles = jelly, but when I run the code I get "Error in code! Expected variable ‘result’ to be defined! I tried everything I know, but I’m stuck. Please help so I can progress.

Hello, @script8879255297.

Welcome to the forum.

In the last line of code, all you need to do is change “burger patty” to “peanut butter” and “pickles” to “jelly”.
Like so:

result = makeSandwich('peanut butter', 'jelly')

Think of the print statement as causing a side-effect , it makes your function write some text out to the user, but it can’t be used by another function.

I’ll attempt to explain this better with some examples, and a couple definitions from Wikipedia.

Here is the definition of a function from Wikipedia

A function, in mathematics, associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output…

Think about that for a second. What does it mean when you say the function has a value?

What it means is that you can actually substitute the value of a function with a normal value! (Assuming the two values are the same type of value)

Why would you want that you ask?

What about other functions that may accept the same type of value as an input ?