Reputation: 2295
I quite regularly see some code like this:
const a = !!b && b.c === true;
I suppose the idea is to not have the a variable nullable, but in that case what is the difference with this code:
const a = b?.c === true
Is there a fundamental difference in between the two?
Upvotes: 2
Views: 1092
Reputation: 51850
Both expressions have the same result.
The crucial difference is: compatibility
In pure JavaScript, the ?.
operator is really recent: See the Browser compatibility chart on MDN. My current browser, for example, (today is 2020-03-11, and my Linux system is running Firefox 73) does not support the b?.c
syntax.
The b?.c === true
version could simply not be written before ES2020 and will not work as is on your client's browser if he/she hasn't updated to recent builds to this day: "recent" would mean "bleeding edge"...
As mentioned by jonrsharpe in his comment, the ?.
operator is also available through transpiled languages (TypeScript, CoffeeScript, Babel, etc.), with various dates of support.
Upvotes: 0
Reputation: 323
This is more a JavaScript side of a problem...
The &&
operator returns the first falsy value, so 0
, ''
, undefined
, NaN
or null
would be the value of const a
. If you want a boolean then the !!
syntax is the most common way to ensure it being a Boolean.
If I'm not completely wrong on this the optional chaining (?.
) just stops the execution on undefined or null values and returns undefined.
Upvotes: 1
Reputation: 370779
If the situation is such that b
, if it exists (isn't undefined or null), will be an object, then no, there isn't any difference between those two.
The largest reason why you probably see someVar && someVar.someProp
(or !!someVar && someVar.someProp
) and variations is that optional chaining is pretty new syntax. It will only exist in recently-updated codebases (running TypeScript 3.7 or above).
But if a variable may be falsy, but is not necessarily an object - for example, if it's 0, NaN, false, or the empty string, then those constructs are not equivalent. Optional chaining with ?.
will short-circuit to undefined
only if expression to the left of the ?.
is null
or undefined
. Other falsy values will continue to have their properties be evaluated as normal.
Upvotes: 0