Coding for Kids

Functions: Returning Values

Returning values

A function can return a value. Sometimes you just need a function to do something, like putting on your jacket. Other times, you want information sent back to you, so you can use it somewhere else, like calculating area.

To have information sent back to you, use the return keyword. This only works inside of functions. When the computer sees this in the function, it stops what it's doing and goes back to where it was when the function was called. It's sort of like it you had your jacket on halfway and someone yelled return (or stop!). You'd have half a jacket on.

If you just use return without a value, then you get back undefined. If you don't use return at all, that's what a function normally returns (like in our putOnJacket() example). Sometimes that's fine. However, you can send back any kind of variable you want, including a function. Just include it after the return keyword.

Saving a returned value

If you're going to return a value, you usually want to save it to a variable and use it later. (There are exceptions.) This is easy! Just create a variable like normal with let and a name and then set it equal to the function call.

Using a return value immediately

You can also use a return value inside a conditional check or some other function that needs its value.

This pops up an alert saying, "It's another snowy day!"

Assigning an existing function to a variable

It is also possible to assign a function to a variable. This is different than assigning a function call. This lets the new variable name act as if it's the original function.

It's time to return to our currently functional program!

—Dr. Wolf