var nullValue = null;
var undefinedValue;
var trueValue = true;
nullValue ?? undefinedValue ?? trueValue
nullValue || undefinedValue || trueValue
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Nullish coalescing | |
Logical OR |
Test name | Executions per second |
---|---|
Nullish coalescing | 6961844.5 Ops/sec |
Logical OR | 6928438.0 Ops/sec |
Let's break down the benchmark and explain what's being tested.
What is being tested?
The benchmark measures the performance difference between two different approaches to handle null
or undefined
values:
null
or undefined
. It's denoted by three consecutive question marks (??
) followed by the desired default value.|
) operator, which is commonly used in programming languages like C and Python.Options comparison
The benchmark compares these two approaches to see which one is faster:
Pros of Nullish coalescing:
Cons of Nullish coalescing:
Pros of Logical OR operators:
Cons of Logical OR operators:
Library and special JavaScript feature
There are no libraries mentioned in this benchmark. However, note that ECMAScript 2020 features like nullish coalescing were introduced as a standard, which means they're now widely supported across modern browsers.
Special JS feature or syntax
The benchmark uses the new nullish coalescing syntax (??
). If you're not familiar with this syntax, it's similar to the ternary operator in C-like languages:
x ?? y; // equivalent to x || (x === undefined ? y : x)
This syntax is supported in modern JavaScript engines and browsers.
Alternatives
Other approaches to handling null
or undefined
values include:
const value = getValue(); const result = value !== undefined ? value : defaultValue;
if (value === null || value === undefined) { return defaultValue; } else { return value; }
?.
): const result = object?.prop ?? defaultValue;
These alternatives are more verbose and may not be as efficient as Nullish coalescing, but they're still valid ways to handle null/undefined values in JavaScript.