Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 61 ยท Functions

Functions

Learn how to declare and call Dart functions: return types, void, arrow syntax, nested functions, lexical scope and recursion, with runnable stand-ins.

A function is a named block of code that you can run whenever you need it. Functions let you give a name to an idea, reuse it, test it and keep main short. In Dart, functions are also objects, which opens the door to the techniques in First-class functions. This lesson covers the basics: declaring, calling, returning values, scope and recursion.

You have already used main and print. Now you will write your own. The Dart code is read-only, and the TypeScript stand-ins run on the site and mirror the same ideas.

Declaring and calling a function

A function declaration has a return type, a name, a parameter list and a body.

DART
int square(int n) {
  return n * n;
}

void main() {
  print(square(5)); // 25
}
  • int before the name is the return type: the kind of value the function gives back.
  • square is the name. Dart style uses lowerCamelCase for functions.
  • (int n) declares one parameter called n of type int.
  • return n * n; ends the function and hands the result to the caller.

Functions are declared at the top level of a file, next to main. Their order in the file does not matter: main can call square even if square is written below it.

When you call a function, the values you pass are called arguments. Dart checks them against the parameter types before the program runs, so square('five') is a compile-time error.

TypeScript Declaring and calling functions (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

void and functions without a return

If a function does not return a useful value, give it the return type void:

DART
void announce(String message) {
  print('>> $message');
}

A void function can still use a bare return; to leave early. It cannot be used as a value, so var x = announce('hi'); is rejected by the analyzer.

Dart lets you leave the return type out, and then it is treated as dynamic. That is allowed but discouraged: write the type so readers and the compiler know what to expect. Public functions should always declare their types.

Arrow syntax

When the body is a single expression, you can replace the braces and return with =>:

DART
int square(int n) => n * n;

bool isAdult(int age) => age >= 18;

String shout(String text) => '${text.toUpperCase()}!';

The arrow form means "return the value of this expression". It is not a shortcut for any code: the right side must be one expression, not several statements. => print('hi'); is valid because print(...) is an expression, but you cannot put an if statement or a loop after the arrow. Use arrows for short, pure functions and braces when the body does more than one thing.

Return values

A function that declares a non-nullable return type must return a value on every path. The analyzer reports an error if some path ends without a return:

DART
String sizeOf(int n) {
  if (n < 10) {
    return 'small';
  } else if (n < 100) {
    return 'medium';
  }
  return 'large'; // every path ends with a return
}

To return several values at once, return a record, as explained in Records:

DART
(int min, int max) range(List<int> numbers) {
  var lo = numbers.first;
  var hi = numbers.first;
  for (final n in numbers) {
    if (n < lo) lo = n;
    if (n > hi) hi = n;
  }
  return (lo, hi);
}

void main() {
  final (low, high) = range([4, 9, 1, 7]);
  print('$low to $high'); // 1 to 9
}

If you must return nothing in a nullable position, return null with a nullable type such as int?. The meaning of ? is covered in Null safety.

TypeScript Arrow functions, early returns and tuples (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Scope: where a name is visible

Dart uses lexical scope: you can tell where a variable is visible by reading the code. A variable declared inside curly braces is visible in those braces and in any block nested inside them. It is not visible outside.

DART
final appName = 'Notes'; // top level: visible everywhere in the library

void main() {
  var count = 1;          // visible in main and the blocks inside
  if (count > 0) {
    var message = 'positive'; // visible only in this if block
    print('$appName: $message');
  }
  // print(message); // error: undefined name 'message'
}

A variable in an inner block can shadow a name from an outer scope. Avoid it, because it makes the code harder to follow.

flowchart TD
    G["Top level: appName"] --> M["main(): count"]
    M --> I["if block: message"]
    I -.->|"can read"| M
    I -.->|"can read"| G

Inner scopes can read names from the scopes around them, but not the other way round.

Nested functions

You can declare a function inside another function. The inner function can read the outer function's variables, and nobody outside can call it.

DART
String formatPrice(double amount) {
  String twoDecimals(double v) => v.toStringAsFixed(2);
  return '\$${twoDecimals(amount)}';
}

Local helper functions keep related code together without cluttering the file's namespace.

TypeScript Scope and nested functions (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Recursion

A function can call itself. This is called recursion, and it is a natural fit for problems that contain smaller copies of themselves. Every recursive function needs a base case that stops the calls, otherwise it recurses until the stack overflows.

DART
int factorial(int n) {
  if (n <= 1) return 1;          // base case
  return n * factorial(n - 1);   // smaller problem
}

int fibonacci(int n) => n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);

void main() {
  print(factorial(5));   // 120
  print(fibonacci(10));  // 55
}

Reading factorial(4): it returns 4 * factorial(3), which waits for 3 * factorial(2), then 2 * factorial(1), and the base case returns 1. The multiplications then happen on the way back up.

Two cautions. The naive fibonacci recomputes the same values over and over and becomes very slow for larger n; an iterative loop or caching fixes that. And Dart does not optimize tail calls, so a recursion that is hundreds of thousands of levels deep throws a StackOverflowError. Loops from the loops lesson are the safer choice for long repetitions.

On the Dart VM, int is a 64-bit value, so factorial(20) fits and factorial(21) wraps around silently. When compiled to JavaScript for the web, integers behave like JavaScript numbers instead. Keep that in mind when writing numeric code that must run in both places.

TypeScript Recursion and its base case (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which return type should a function use when it does not return a value?

    void means the function produces no useful result. Never is for functions that never return normally, such as one that always throws.
  2. 2. What does int twice(int n) => n * 2; mean?

    The arrow form returns the value of one expression, so no return keyword or braces are needed.
  3. 3. Where is a variable declared inside an if block visible?

    Dart uses lexical scope. A variable lives in the braces where it is declared.
  4. 4. What must every recursive function have?

    Without a base case the function calls itself forever and the stack overflows.

Summary

  • A function has a return type, a name, parameters and a body; call it with arguments.
  • Use void when nothing is returned, and always declare types on public functions.
  • => returns a single expression; use braces for anything longer.
  • Return a record to give back several values.
  • Variables are visible in the block where they are declared and the blocks inside it.
  • Recursion needs a base case; Dart has no tail-call optimization, so prefer loops for very deep repetition.

Next: positional, named and optional parameters.