Learn how to define and use functions in CQL.

CQL allows you to define your own functions to perform custom operations and improve the maintainability of your queries.

Functions enable you to encapsulate complex logic, avoid repeating code, and make queries more readable and easier to understand.

Function definition

The syntax for defining functions in CQL is almost the same as in JavaScript for arrow functions. An important difference is that CQL has no concept of blocks, so the body of the function must always be a single expression.

Here is an example of a function that takes multiple parameters:

let price = (value, discount) => value - (value * discount);
price(100, 0.1) // 90
Try in Playground

For single-parameter functions, you can omit the parentheses around the parameter list:

let welcome = subject => "Hello, " & subject & "!";
welcome("world") // Hello, world!
Try in Playground

You can also define parameterless functions:

let welcome = () => "Hello, " & location's city & "!";
welcome() // Hello, <Countru>!
Try in Playground

Because the body expression has access to variables defined in the parent context, you can access the user's location without having to pass it as a parameter.

Function calls

Function calls allow you to invoke functions with specific inputs, known as arguments. CQL supports different ways to pass arguments to functions, as described below.

No arguments

If a function does not take any parameters, you can just call it without any arguments:

let hello = () => "Hello, world!";
hello() // "Hello, world!"
Try in Playground

Note that calling a function with arguments when it does not expect any will work, but the arguments will be ignored. However, attempting to call a function without passing the required arguments will result in an error.

Positional arguments

Positional arguments refer to the practice of passing arguments to a function in the same order as they appear in the function definition.

Suppose you have a function that takes three parameters:

let calculate = (a, b, c) => a + b * c;
calculate(1, 2, 3) // 7
Try in Playground

In the example above, the parameters a, b, and c receive the values 1, 2, and 3, respectively.

Named arguments

You can also call functions with arguments specified by their names, in which case the order does not matter.

In the example below, we provide named arguments when calling the calculate function:

let calculate = (a, b, c) => a + b * c;
calculate(c: 3, b: 2, a: 1) // 7
Try in Playground

It's also possible to mix both positional and named arguments in a function call — as long as all positional arguments are provided before the named arguments.

Here is an example of a function call using both argument types:

let calculate = (a, b, c) => a + b * c;
calculate(1, c: 3, b: 2) // 7
Try in Playground