First-element macro

Learn how to get the first element of a collection.

This macro gets the first element of a collection.

To determine the first element, this macro uses the order of the collection and not the key or index of the element.

Note that trying to get the first element of an empty collection results in an error, so be sure to provide a default value in cases where the collection might be empty.

Croct's mascot neutral
Why not return null instead?

An error helps distinguish between empty collections and those with null elements, so you can easily handle both cases.

Syntax

This macro has the following syntax:

first of /*<collection>*/
Try in Playground

You can also prefix the macro with a definite article for readability:

the first of /*<collection>*/
Try in Playground

Parameters

These are the supported parameters:

collection

A non-empty collection from which you want to get the first element.

Examples

Here is an example of how to get the first element of a list:

first of [1, 2, 3] // 1
Try in Playground

You can also get the first element of a map:

first of ["a": 1, "b": 2, "c": 3] // 1
Try in Playground

To get the first key of a map, you can use the keys macro:

first of keys of ["a": 1, "b": 2, "c": 3] // "a"
Try in Playground

If the collection might be empty and you want to return null instead of an error, you can use a fallback operator:

first of /*<collection>*/ or else null
Try in Playground