KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: .first() vs. [0] For Getting the First Element of a Selection
PRODUCT: 4D | VERSION: 20 | PLATFORM: Mac & Win
Published On: July 15, 2024

In most cases the two following lines of code are identical when executed. However, when Table is empty, the first line will return an error and the second will return null. In most cases it is better to use .first() because it protects against empty tables and allows for less code to be written since an explicit check for empty Tables is not necessary before calling the function:

$e:=ds.Table.all()[0] // The indice: 0 is outside the entity selection.

$e:=ds.Table.all().first() // No error when Table is empty


This prevents having to nest the code in conditions like this:

If (ds.Table.all().length # 0)
   $e:=ds.Table.all()[0]
End if