KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Avoid Null Collection Errors in For Each Statement with Short-Circuit OR Operator
PRODUCT: 4D | VERSION: 21 | PLATFORM: Mac & Win
Published On: November 18, 2026
When looping over a collection that is stored in an object property, sometimes the property may be null or may not exist at all. In that case, the "For each" statement raises error 314: "For each" statement expects a collection or an object. Testing for null with an If statement before every loop would work, but it adds extra lines and additional level of nesting.



A shorter option is the short-circuit OR operator (||). It returns the first operand if that expression is truthy; otherwise, returns the second operand. A null collection is falsy, so placing an empty collection as the second operand guarantees that For each always receives a valid collection. For example:
For each ($cmd_t; $obsoleteCommand_o["C_List"] || [])
  $count_t:=$count_t+" "+$cmd_t+" "+String($obsoleteCommand_o["C_List"][$cmd_t])
End for each

In the above example, if $obsoleteCommand_o has no "C_List" property, the expression evaluates to the empty collection, the loop body runs zero times, and no error is raised. If the property does hold a collection, it is truthy and is returned as is, so the loop behaves exactly as before. Note that in versions that do not support the [] collection literal, the "New collection" command can be used as the second operand instead.