2

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?

4

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Arguably !!(b && b.c) might be nicer…
bug potential as this would change the program logic from b.c needs to be equal to true to b.c needs to be truthy
True, though seeing this code I would assume the author is simply hyper vigilant about types instead of being more… dynamic Javascript-y about them. The difference between true and truthy probably wouldn't make a difference. Of course, if it does, then yes, you should rather use the explicit comparison.
In this case, a will always be the literal true or false, not "0, '', undefined, NaN or null "
0

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.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.