Answer#
JavaScript has two "no value" values (null and undefined), a missing property that reads as undefined, and a notion of truthiness that treats 0, "", NaN and null as false. Rust has none of these: a value that may be absent has the type Option<T>, which is either Some(value) or None, and a condition must be a bool.
| JavaScript | Rust |
|---|---|
u.address?.city | and_then on the Option (see the example below), or ? inside a function that returns Option |
x ?? 3 | x.unwrap_or(3) |
x followed by the logical-or operator and 3 (also replaces 0 and "") | no equivalent: write the check you mean, such as if x == 0 { 3 } else { x } |
if (x) on a number or string | if x != 0, if !s.is_empty(), or if let Some(v) = x |
obj.key === undefined | map.get("key").is_none() |
if (v == null) throw new Error(...) | let v = v.ok_or(error)?; |
Node.js (v22.19.0) first:
const a = { address: { city: "Pune" }, retries: 0 };
const b = {};
for (const u of [a, b]) {
const city = u.address?.city ?? "unknown";
console.log(city, u.retries ?? 3, u.retries || 3);
}
console.log([] ? "truthy" : "falsy", "" ? "truthy" : "falsy", 0 ? "truthy" : "falsy");Pune 0 3
unknown 3 3
truthy falsy falsyLook at the first line: for a, retries is 0. u.retries ?? 3 keeps the 0; u.retries || 3 replaces it with 3, which is a classic bug that is often a feature by accident. The Rust port has to say which one it means:
#[derive(Debug)]
struct Address { city: Option<String> }
#[derive(Debug)]
struct User { address: Option<Address>, retries: Option<u32> }
fn main() {
let a = User { address: Some(Address { city: Some("Pune".into()) }), retries: Some(0) };
let b = User { address: None, retries: None };
for u in [&a, &b] {
// JS: u.address?.city ?? "unknown"
let city = u.address.as_ref().and_then(|a| a.city.as_deref()).unwrap_or("unknown");
// JS: u.retries ?? 3 (0 is kept) u.retries || 3 would turn 0 into 3
let retries = u.retries.unwrap_or(3);
println!("{city} {retries}");
}
// there is no "falsy": a number is not a condition
let n = 0;
println!("{}", if n != 0 { "truthy" } else { "zero" });
println!("{:?}", "".is_empty());
}Pune 0
unknown 3
zero
trueSome(0).unwrap_or(3) is 0, matching ??. Writing a condition like if n { ... } with an integer does not compile, so the "empty means false" bug cannot be ported by accident.
How to do it#
- For each variable, property or parameter that can be
nullorundefined, make itOption<T>. A property that is always present is a plainT. - Replace
a?.b?.cwith a chain ofand_then(ormap, when the step cannot fail), or write a small function returningOption<T>and use?inside it. - Replace
x ?? dwithunwrap_or(d), orunwrap_or_else(|| ...)when the default is expensive to build. - Replace
||defaults and truthiness tests with explicit comparisons, and decide for each whether0and""should count as missing. - For JSON, let serde do it:
Option<T>fields accept both a missing key andnull(see the thread on TypeScript types and serde).
Common mistakes#
- Using
unwrap()on anOptionas the translation of!. If the value isNonethe program panics. - Mixing "missing" and "empty".
Option<String>(absent) andString::new()(present but empty) are different; JavaScript often treats them the same. - Writing
Option<Option<T>>to model bothnullandundefined. Decide what the difference means in your data first.
Related questions#
Is Option slower than a null pointer?#
For references and Box, Option<Box<T>> is the same size as a plain pointer, because the compiler uses the null value for None (shown in the thread on C structs). This thread did not measure speed.
What replaces typeof x === "undefined" for a variable?#
Nothing: a variable that exists has a value. The question belongs to the type, Option or not.
Sources#
- The Rust Book, "The Option Enum": https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html#the-option-enum-and-its-advantages-over-null-values
std::option::Option: https://doc.rust-lang.org/std/option/enum.Option.html