'Null Propagation operator in Node.js
I need to do something similar to bar = (foo == null) ? null : foo.bar
Is Null Propagation Operator (?.) available in Node.js? If no, Is this a proposal for the newer version?
[Edit] To add more clarity, I want to avoid NPE when accessing foo.bar (when foo is not defined) and the expression should return a null instead.
Solution 1:[1]
Update based on below comment:
The below code will evaluate to the value of foo if foo is falsey (null, undefined, false, empty string, etc), or to foo.bar if foo is not falsey. Like the || operator, the && operator also returns whatever it evaluates last. If foo is falsey, then it will abort evaluation and return the value of foo. If foo is not falsey, then it will continue and evaluate foo.bar and return whatever that is.
foo && foo.bar
Original answer:
You can accomplish this in Javascript using the or operator, ||
The or operator does not necessarily evaluate to a boolean. It returns the last argument that it evaluates the truthiness of.
So, building off of your example, the following code sets foo equal to foo.bar.
foo = null || foo.bar
And the following compares foo to foo.bar (I'm not sure if the double =s in your code was intentional or not. If it was intentional, then consider using triple =s instead)
foo === (null || foo.bar)
This concept is frequently used for setting default values. For example, a function that takes an options argument may do something like this.
options.start = options.start || 0;
options.color = options.color || "red";
options.length = options.length || 10;
Just be careful of one thing. In the last line of the above code, if options.length is 0, then it will be set to 10, because 0 evaluates to false. In that scenario, you probably want to do things the "old-fashioned" way:
options.length = options.length === undefined ? 10 : options.length;
Solution 2:[2]
const bar = foo && foo.bar;
This is called Short-circuit evaluation, where second part (part after &&) is only evaluated if the first part is a truthy value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | P-Srt |
