User-defined functions
A user-defined function is a reusable piece of logic declared within a script. Once declared, the function can be called like any built-in function.
Declaration
A function declaration begins with the func keyword, followed by a name, a parameter list in parentheses, and a body.
There are two body forms: arrow and block.
Arrow form
The arrow form uses => followed by a single expression. The result of the expression is the return value.
Use the arrow form when the function body is a single expression.
Block form
The block form encloses the function body in braces. Use it when the function needs intermediate bindings or multiple steps.
An explicit return sets the block function’s result. If execution reaches the closing brace without one, the function completes successfully with none. Arbitrary expression statements are evaluated and discarded rather than returned implicitly; use the arrow form for a single expression.
An empty block is therefore a valid effect-only function:
Returning a for result
A block function can return a loop directly with return for. The array produced by the loop becomes the function result.
This uses the same loop result as a parenthesized for; it does not add another wrapper. return distinct for applies the normal return-level deduplication directly to the loop result.
A final standalone loop is not promoted into a function result. A collecting loop still executes, but its array is discarded; a returnless braced loop executes without creating an array. In both cases the function falls through with none:
Likewise, func value() { 42 } evaluates 42 as an expression statement and returns none. Write func value() => 42 or func value() { return 42 } to return the value. Use return for when the function should return a loop’s collected array.
Parameters
Parameters are listed inside parentheses, separated by commas.
A function may have no parameters:
Parameters are positional. The caller must provide exactly the number of arguments the function expects.
Capturing outer variables
A function body can read variables from the enclosing scope.
If the outer variable is declared with var, the function can also modify it:
Variables declared with let are immutable and cannot be reassigned inside a function.
Nesting functions
Functions can be declared inside other functions.
A nested function can access variables from all enclosing scopes, not just the immediately surrounding one.
Using functions in loops
User-defined functions work naturally with for loops and other query constructs.
Function names
Function names follow the same rules as variable names: they must start with a letter or underscore, followed by any combination of letters, digits, and underscores.
Function names are case-sensitive. add and Add are different functions.
Built-in and host functions are documented with canonical lowercase names. User-defined function names remain case-sensitive and may use the style preferred by the script author.