All lessons

Functions

8 min · Dart

Package code under a name so you can reuse it.

Dart · Functions0/5 cleared

Enemy 1 of 5

Defining a function with types

Once a program grows past a few lines, you'll often want to run the same logic in more than one place — doubling a number, validating input, formatting text. A function lets you write that logic exactly once, attach a name to it, and then call it by name wherever you need it, rather than repeating the same statements throughout the program.

This also makes programs easier to trust and reason about: once you've verified that double(n) correctly doubles a number, you can call double(5) anywhere in the program without re-reading its internals each time — much like how you don't re-derive how a calculator's multiply button works every time you press it.

Dart functions declare their return type, name, and parameter types up front: int double(int n) { ... } means this function returns an int, is called double, and takes one parameter n which must be an int. This is a meaningfully different style from PHP's or Ruby's untyped parameters — Dart checks these types at compile time, so calling double('five') (a string, not an int) would fail to compile rather than causing a confusing runtime error later.

Parameters, like n here, are placeholder variables that receive whatever value is passed in when the function is called — inside int double(int n), n holds whatever number you pass to double(...).

return hands a value back to whoever called the function, and immediately stops the rest of the function from running. Because the function's declared return type is int, Dart will flag an error at compile time if you try to return anything that isn't an int (or something Dart can't automatically convert to one) — another safety net that catches mistakes earlier than a dynamically-typed language would.

You
Syntax Skeleton

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 10