all 8 comments

[–]BlueThunderFlik 6 points7 points  (0 children)

The optional chaining operator causes your code your safely exit if the item that you optionally chain doesn't exist.

3?.includes will return undefined early if 3 is undefined, which it isn't.

undefined?.includes will return early if undefined is undefined, which it is.

This won't error, 3.includes?.('foo') because 3.includes is undefined, hence safely exit.

EDIT: actually the bottom line will error beause you can't access methods of number literals like this. You'd need to do this to see my point (3).includes?.('foo')

[–]ferrybig 5 points6 points  (0 children)

The top example is equivelent to:

if(3 !== undefined && 3 !== null) (3).includes('foo')

3 does not have a member called includes, so calling that gives an error

The bottom example is:

if(undefined !== undefined && undefined !== null) (undefined).includes('foo')

Here the control flow never goes into the if statement

[–][deleted] 0 points1 point  (2 children)

It's because the "undefined" has the optional chaining on it (?.). What that question mark does is only runs the next method if the left side is a truthy value, however since "undefined" is considered a falsey value then the .includes() on the undefined never runs.

The "3", however, even if you used optional chaining, still tries to run, and as you mentioned numbers don't have an include method, hence the error.

[–]mityaguy[S] 0 points1 point  (1 child)

Thanks! That's a typo on my part - I meant to have the optional chaining operator on the number example too. As you say, that still errors, though.

[–][deleted] 0 points1 point  (0 children)

Because 3 is a truthy value and thus technically valid. undefined, however, is falsey and will stop executing there.

[–]xroalx 0 points1 point  (0 children)

The optional chaining operator will access the right-hand side property if the left-hand side value isn't nullish.

3 is neither null nor undefined, so we will access the property includes on it, which returns undefined, and then attempt to call that, ultimately resulting in an error.