Anonymous functions
An anonymous function is a function that doesn’t have a name, and is typically used as an argument to another function. In Fauna, functions are defined an managed using the Function API.
See User-defined functions in the migration document for FQL v10 and FQL v4 UDF interoperability. |
Declaration and scope
Fauna Query Language (FQL) uses the JavaScript-style short-form arrow syntax to declare an anonymous function. Function declaration has the generalized form:
([param[, param]]) => {[statement[ statement …] expression]}
The param can be any valid identifier including a single underscore (_), which can be repeated in the param list.
An anonymous function block can include field access constructs, operators, function arguments, and nested blocks. Variables declared in an anonymous function block are scoped to the anonymous function, but the function can access the variables in the parent block.
The last expression is the return value of the function. There is no
explicit return
keyword.
Simplified syntax
For a function with one parameter, the ()
enclosing the parameter can be
omitted. If the function body consists of a single-line expression, the {}
block can also be omitted. These examples are equivalent and return a value
of 6
:
Short form predicates
Some schema entities and built-in functions, such as
where()
, accept an
anonymous function as input parameter. This example declares an anonymous
function as a where()
predicate.
This example returns all customers with a zip code of 20002
:
{
"data": [
{
"id": "347323742580376064",
"coll": "Customer",
"ts": "2022-11-03T16:23:02.860Z",
"firstName": "Bob",
"lastName": "Brown",
"address": {
"street": "72 Waxwing Terrace",
"city": "Washington",
"state": "DC",
"zipCode": "20002"
},
"telephone": "719-872-8799",
"creditCard": {
"network": "Visa",
"number": "4916112310613672"
}
}
]
}
For simple anonymous functions, the dot prefix provides a shorthand notation that can be used that omits the parameter name. This is equivalent to the preceding example:
{
"data": [
{
"id": "347323742580376064",
"coll": "Customer",
"ts": "2022-11-03T16:23:02.860Z",
"firstName": "Bob",
"lastName": "Brown",
"address": {
"street": "72 Waxwing Terrace",
"city": "Washington",
"state": "DC",
"zipCode": "20002"
}
}
]
}
The dot notation distinguishes field names from variable names in the same scope.
Multiple occurrences of bare field access apply to the same implicit parameter:
`.address.zipCode == "20002" && .firstName == "Bob"`
Is this article helpful?
Tell Fauna how the article can be improved:
Visit Fauna's forums
or email docs@fauna.com
Thank you for your feedback!