Nullish Coalescing Operator (??)
The nullish coalescing operator (??
) provides a way to define a fallback value when dealing with null
values. It returns the right-hand operand when the left-hand operand is null
, otherwise it returns the left-hand operand.
Syntax
Description
The ??
operator is particularly useful when you want to provide default values for potentially null variables or expressions. Unlike logical OR (||
), which returns the right-hand operand for any falsy value (including 0
, ""
, false
), the nullish coalescing operator only does this for null
values.
This makes it ideal for cases where 0
, empty strings, or false
are valid values that should be preserved.
Examples
Basic Usage
Comparison with Logical OR
Working with Objects
Working with Database Values
Chaining Nullish Coalescing
You can chain the ??
operator to try multiple fallback values:
Nullish Assignment (??=)
OSL also supports the nullish assignment operator (??=
), which assigns the right-hand value only if the left-hand value is null
:
Notes
The
??
operator only considersnull
as the trigger for using the fallback valueEmpty strings,
0
, andfalse
are all considered valid values and will not trigger the fallbackThe
??
operator has relatively low precedence, but explicit parentheses can be used for clarityThe nullish coalescing operator is particularly useful when working with database values, API responses, or optional object properties
Last updated
Was this helpful?