?? : Null Coalescing Operator
On this page
Summary
Provide a fallback value when an expression evaluates to null or undefined.
Syntax
Precedence
Priority level in expression evaluation (1 = highest, 10 = lowest): 8
Evaluated after: ^, *, /, %, +, -, <, <=, >, >=, ==, !=
Evaluated before: &&, ||
Operands
| Position | Type | Description |
|---|---|---|
| Left | Any | Expression that might be null |
| Right | Any | Fallback value if left is null |
Returns
Type: Same as operands
Returns the left operand if it’s not null, otherwise returns the right operand.
Examples
Default User Name
Data (with name):
doc.Params["model"] = new {
user = new {
name = "John Doe"
}
};
Output:
<h2>Welcome, John Doe!</h2>
Data (without name):
doc.Params["model"] = new {
user = new {
name = (string)null
}
};
Output:
<h2>Welcome, Guest!</h2>
Missing Description
Data:
doc.Params["model"] = new {
products = new[] {
new { name = "Widget A", description = "High quality widget" },
new { name = "Widget B", description = (string)null },
new { name = "Widget C", description = "Premium widget" }
}
};
Output:
<div class="product">
<h3>Widget A</h3>
<p>High quality widget</p>
</div>
<div class="product">
<h3>Widget B</h3>
<p>No description available</p>
</div>
<div class="product">
<h3>Widget C</h3>
<p>Premium widget</p>
</div>
Optional Contact Information
Nested Property Access
Data (nested null):
doc.Params["model"] = new {
user = new {
address = (object)null
}
};
Output:
<p>City: Unknown</p>
Default Values in Lists
Data:
doc.Params["model"] = new {
items = new[] {
new { name = "Item 1", category = "Electronics", price = 99.99m, notes = "In stock" },
new { name = "Item 2", category = (string)null, price = (decimal?)null, notes = (string)null }
}
};
Output:
<tr>
<td>Item 1</td>
<td>Electronics</td>
<td>$99.99</td>
<td>In stock</td>
</tr>
<tr>
<td>Item 2</td>
<td>Uncategorized</td>
<td>$0</td>
<td>-</td>
</tr>
Chaining Multiple Defaults
Default Image
Notes
- Returns left operand if not null/undefined, otherwise returns right operand
- Very useful for providing default values
- Can chain multiple null coalescing operators
- Evaluates left-to-right when chained
- Does not check for empty strings - only null/undefined
- More concise than
default - Similar to C# null-coalescing operator
- Use
ifError()function for error handling instead of null checking
Null vs Empty String
The ?? operator only checks for null/undefined, not empty strings: