It can be hard to keep up with new features in JavaScript. I hadn’t used the nullish coalescing operator (??
) before, so I gave it a try in the Node.js REPL (Read Evaluate Print Loop) mode to better understand how it works. Node.js runs in REPL mode when you run node
with no arguments. It’s really handy for quickly trying things out.
This is how you use nullish coalescing operator:
const example = useThisValueIfNotUndefinedOrNull ?? "default value";
These examples show how it behaves with different types of values:
$ node
Welcome to Node.js v14.15.4.
Type ".help" for more information.
> let useThisValueIfNotUndefinedOrNull;
> let example;
> example = useThisValueIfNotUndefinedOrNull ?? "default value";
'default value'
> useThisValueIfNotUndefinedOrNull = null;
> example = useThisValueIfNotUndefinedOrNull ?? "default value";
'default value'
> useThisValueIfNotUndefinedOrNull = 42;
> example = useThisValueIfNotUndefinedOrNull ?? "default value";
42
> useThisValueIfNotUndefinedOrNull = "";
> example = useThisValueIfNotUndefinedOrNull ?? "default value";
''
> useThisValueIfNotUndefinedOrNull = false;
> example = useThisValueIfNotUndefinedOrNull ?? "default value";
false
The nullish coalescing operator is supported in Node.js >= 14.0, and all modern browsers. You can learn more about it in the MDN Web Docs.