How To Write Expressions If a Referenced Field Might Not Be Available Or Its Value Could Be Null

To write efficient expressions that handle situations where a referenced field might not be available or the field's value could be null, use the JavaScript optional chaining operator (?.) and the nullish coalescing operator (??). These operators are supported in standalone JS files as well as in HTML/JSON file expressions.

To avoid exceptions that might occur because of a missing field, which can happen when a field is optional, use the optional chaining operator (?.). The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid. The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

For example, when your expression is $fields.USMType_c?.value(), JavaScript will check to make sure that $fields.USMType_c is not null or undefined before trying to access $fields.USMType_c?.value(). If $fields.USMType_c is null or undefined, the expression automatically short-circuits, returning undefined. See optional chaining operator.

To avoid exceptions that might occur because of a missing field value, use the optional nullish coalescing operator (??). Using the $fields.USMType_c?.value() ?? 42 example, if the value is nullish, 42 will be returned. This sets a default value when no value is found. See Nullish coalescing operator.