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

leftExpr ?? rightExpr

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

// With variables that might be null
username = null
defaultName = "Guest"

displayName = username ?? defaultName
log displayName
// Outputs: "Guest"

// With non-null values
username = "Alice"
displayName = username ?? defaultName
log displayName
// Outputs: "Alice"

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 considers null as the trigger for using the fallback value

  • Empty strings, 0, and false are all considered valid values and will not trigger the fallback

  • The ?? operator has relatively low precedence, but explicit parentheses can be used for clarity

  • The nullish coalescing operator is particularly useful when working with database values, API responses, or optional object properties

Last updated

Was this helpful?