See all glossary terms

Return (Function)

return is a keyword that ends a function, and sends a value back to the caller.
In GDScript, you can return any value from a function, but this return value should match the return type declared in the function's signature.
For example, this function returns an integer:
func return_five() -> int:
  return 5
But if I wrote this, Godot would give me an error:
func return_five() -> int:
  return "five"
Because "five" is a string, not an integer.

Branches

This function is an error too. Can you spot it?
var should_return_five := true

func return_five() -> int:
  if should_return_five == true:
    return 5
  else:
    return null
The declared return type is an int, but the effective return type is a mix of either int, or null. The two don't match. To make the function valid, I could return 0 in the else branch
This example is obvious, but there are cases where Godot might not be able to tell if a function's return matches the signature, even if you're able to. Consider the below:
var default_return = 0

func return_five() -> int:
  if some_condition:
    return 5
  return default_return
In this case, Godot can't tell if the function will always return an integer, because default_return is not typed. While you know it's an int, there's no guarantee it won't change. If you're sure it won't, you can add a type hint:
func return_five() -> int:
  if some_condition:
    return 5
  return default_return as int
The as keyword casts the variable. is a way to tell Godot "I know what I'm doing, trust me".
NOTE:
This is just a simplified example; in this case, typing default_return would be a clearly better solution than using as.

Returning nothing

While both mathematical functions and programming functions share the same name, they are not the same thing.
A function can indeed work like a math function:
func multiply_by_ten(number: int) -> int:
  return number * 10
That's what we call a pure function, because it is self contained. It doesn't use anything beside its arguments.
But it can also affect an external variable, without returning anything:
var counter := 0

func increment_counter(number: int) -> void:
  counter += number
Affecting the world around is what we call a side effect. Notice the lack of return in this function; it does something, but doesn't return anything.
Of course there's nothing stopping us from writing a function that does both. This function multiplies by 10, returns the result, but also counts how many times it was called:
var counter := 0

func multiply_by_ten(number: int) -> int:
  counter += 1
  return number * 10
This is a function with both side effects (affects the world around it) and a return value. Those functions are very common.