let a = null
return a ?? "b";
let v = null
if(v !== null) {
return a;
}
return "b";
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Nullish coalescing | |
If chains |
Test name | Executions per second |
---|---|
Nullish coalescing | 1010312448.0 Ops/sec |
If chains | 1007971776.0 Ops/sec |
This benchmark on MeasureThat.net compares two ways of handling potential null values in JavaScript:
1. Nullish Coalescing Operator (??
):
??
operator, which returns the left operand if it's not null or undefined, otherwise it returns the right operand. In this case: let a = null; return a ?? "b";
.2. If-Chain:
if
statement to check if the variable (v
) is not null. If it's not, it returns a value (a
). Otherwise, it returns "b"
.let v = null;
if(v !== null) {
return a;
}
return "b";
Pros and Cons:
Nullish Coalescing (??
):
If-Chain:
Other Considerations:
Alternatives:
condition ? value1 : value2
): This can be used as a shorter alternative to the if-chain, but it might not always be as readable for complex conditions:return v !== null ? a : "b";
Let me know if you have any more questions!