Return values
- Dart course
- Beginner
- Lesson 66/116
- 4 min
Learn to return a value from a function with return.
Return values
A function can return a value; you write the return keyword and a return type. Example: int add(int a, int b) { return a + b; }. This function takes two integers and returns their sum.
The return type tells what the function gives back: int, String, double, bool. When return is reached, the function ends; nothing after it runs.
The caller can store the returned value in a variable: var sum = add(3, 4);. The value 7 now lives in sum. Functions that give back nothing use void.
The return flow
A function stops as soon as it sees return. Lines after it do not run. Example: int first() { return 1; print('Never reached'); } — print is never executed.
You can write multiple returns; the first one reached decides the value. This is handy for conditional returns: if (x > 0) { return x; } return -x;.
void functions can also exit early with return;; in that case they return no value, they only end the function.
Practice Compute the square
Define a square(int n) function that returns n * n. Add a print(square(5)) call inside main.
Starter code
void main() {
// define the square function
// print the result
}Sample solution
int square(int n) {
return n * n;
}
void main() {
print(square(5));
}Expected output
25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the return types
| Term | Meaning |
|---|---|
int |
Integer |
String |
Text |
double |
Decimal |
bool |
Boolean |
2 What happens after return?
- The next line also runs
- It throws
- A loop starts
- The function ends Correct answer
Explanation: return exits the function immediately.
3 The return expression
int add(int a, int b) {
return ____;
}
int add(int a, int b) {
return a + b;
}
Explanation: return sends back the sum.