null-check
null-coalescing
conditional-assignment
programming-tips
code-optimization

Shortest way to check for null and assign another value if not

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Most modern languages provide a null coalescing operator that returns a default value when the expression is null. In C# it is ??, in JavaScript ??, in Python or (with caveats), in Kotlin ?:, and in Swift ??. These operators replace verbose if (x == null) checks with a single concise expression, making null-handling code shorter and more readable.

C# — Null Coalescing Operator (??)

csharp
1// Long form
2string name;
3if (input != null)
4    name = input;
5else
6    name = "default";
7
8// Short form with ??
9string name = input ?? "default";
10
11// Chaining — first non-null wins
12string name = firstName ?? lastName ?? "Anonymous";
13
14// Null coalescing assignment (C# 8+)
15name ??= "default";  // Assigns only if name is null

?? only checks for null. Unlike JavaScript's ||, it does not treat "", 0, or false as needing a default.

JavaScript — Nullish Coalescing (??)

javascript
1// Long form
2let name;
3if (input !== null && input !== undefined) {
4    name = input;
5} else {
6    name = "default";
7}
8
9// Short form with ?? (ES2020)
10let name = input ?? "default";
11
12// ?? vs || — critical difference
13let count = 0;
14console.log(count || 10);   // 10 — || treats 0 as falsy
15console.log(count ?? 10);   // 0  — ?? only checks null/undefined
16
17let text = "";
18console.log(text || "fallback");   // "fallback" — || treats "" as falsy
19console.log(text ?? "fallback");   // ""         — ?? keeps empty string
20
21// Nullish assignment (ES2021)
22let value = null;
23value ??= "default";  // value is now "default"

Python — or Operator (with Caveats)

python
1# Using 'or' — returns first truthy value
2name = input_value or "default"
3
4# CAUTION: 'or' treats all falsy values as needing a default
5count = 0
6result = count or 10  # 10 — wrong if 0 is valid!
7
8text = ""
9result = text or "fallback"  # "fallback" — wrong if "" is valid!
10
11# Safe alternative — explicit None check
12name = input_value if input_value is not None else "default"
13
14# With walrus operator (Python 3.8+)
15# Useful in conditions
16if (value := get_value()) is not None:
17    process(value)

Python has no dedicated null coalescing operator. The or operator works for strings and objects but fails for 0, "", False, and other falsy values.

Kotlin — Elvis Operator (?:)

kotlin
1// Long form
2val name: String = if (input != null) input else "default"
3
4// Short form with ?:
5val name: String = input ?: "default"
6
7// Chaining
8val name = firstName ?: lastName ?: "Anonymous"
9
10// With function calls
11val length = text?.length ?: 0
12
13// Throw on null
14val name = input ?: throw IllegalArgumentException("Name required")
15
16// Return on null
17fun process(input: String?): String {
18    val value = input ?: return "no input"
19    return value.uppercase()
20}

Swift — Nil Coalescing Operator (??)

swift
1// Long form
2let name: String
3if let input = optionalInput {
4    name = input
5} else {
6    name = "default"
7}
8
9// Short form with ??
10let name = optionalInput ?? "default"
11
12// Chaining
13let name = firstName ?? lastName ?? "Anonymous"
14
15// With computed default (lazy evaluation)
16let name = optionalInput ?? expensiveComputation()
17// expensiveComputation() only runs if optionalInput is nil
18
19// Combining with optional chaining
20let count = array?.count ?? 0
21let uppercased = text?.uppercased() ?? "N/A"

PHP — Null Coalescing Operator (??)

php
1// Long form
2$name = isset($input) ? $input : "default";
3
4// Short form with ?? (PHP 7+)
5$name = $input ?? "default";
6
7// Chaining
8$name = $firstName ?? $lastName ?? "Anonymous";
9
10// Null coalescing assignment (PHP 7.4+)
11$name ??= "default";
12
13// Works with arrays and nested access
14$city = $user['address']['city'] ?? "Unknown";
15// No error even if $user or 'address' doesn't exist

Ruby — Conditional Assignment (||=)

ruby
1# Long form
2name = input.nil? ? "default" : input
3
4# Using ||
5name = input || "default"
6
7# Conditional assignment
8name ||= "default"  # Assigns only if name is nil or false
9
10# Ruby 2.3+ safe navigation
11name = user&.name || "Anonymous"

Comparison Table

LanguageOperatorChecks forAssignment form
C#??null??=
JavaScript??null, undefined??=
PythonorAll falsy valuesN/A
Kotlin?:nullN/A
Swift??nilN/A
PHP??null, unset??=
Ruby`\\`nil, false`\\=`

Common Pitfalls

  • Using || instead of ?? in JavaScript: || treats 0, "", false, and NaN as falsy and returns the right-hand side. ?? only triggers on null and undefined. For numeric defaults, count || 10 gives 10 when count is 0, which is usually wrong.
  • Python or treating 0 and "" as needing defaults: value or default returns default when value is 0, "", [], or any falsy value. Use value if value is not None else default for a true null check.
  • Null coalescing with side effects: The right-hand expression is only evaluated if the left is null (lazy evaluation in most languages). But if the right side has side effects (incrementing a counter, making an API call), the behavior depends on whether the left is null — this makes code harder to reason about.
  • Chaining too many operators: a ?? b ?? c ?? d ?? "default" is technically valid but makes it hard to understand the fallback chain. Consider extracting into a function or using a collection-based approach like [a, b, c, d].first { it != null }.
  • Forgetting that ??= does not exist in all languages: Kotlin, Swift, and Python do not have a null coalescing assignment operator. Kotlin uses value = value ?: default and Swift uses if value == nil { value = default }.

Summary

  • C# ??, JavaScript ??, Kotlin ?:, Swift ??, and PHP ?? are null coalescing operators
  • They return the right-hand value only when the left is null (or nil/undefined)
  • JavaScript's ?? differs from ||?? only checks null/undefined, || checks all falsy values
  • Python's or is not a true null coalescing operator — it treats all falsy values as needing a default
  • Use ??= (C# 8+, JS ES2021, PHP 7.4+) for null coalescing assignment
  • Prefer ?? over || when 0, "", or false are valid values that should not be replaced

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms