loading...

Discussion on: 😲🤯The most outstanding new feature in Javascript you need to know about: Optional Chaining

Collapse
marcellothearcane profile image
marcellothearcane

Why

const personFirstName = person?.details?.name?.firstName ?? 'stranger'

Rather than

const personFirstName = person?.details?.name?.firstName || 'stranger'

?

Collapse
lampewebdev profile image
Michael "lampe" Lazarski Author

Good question!
Example time!

const user = {
    auth: {
        isLoggedIn: false
    }
}

const isLoggedIn = user.auth?.isLoggedIn || true
// isLoggedIn would be true!

const isLoggedIn = user.auth?.isLoggedIn ?? true
// isLoggedIn would be false!

As you can see there is a difference in how they work.
The problem with || is that it will return the right value when the left value is falsy. The ?? just checks for null or undefined.

Collapse
joshsanger profile image
Joshua Sanger

Could also consider converting to a true/false value with:

const isLoggedIn = !!(user.auth?.isLoggedIn)
Thread Thread
thecodingalpaca profile image
Carlos Trapet

@joshua I was literally going to say the same thing.
I fail to see the point/usefulness of the '??' operator

Thread Thread
lampewebdev profile image
Michael "lampe" Lazarski Author

There are always alternatives if you can also write

if(user.auth?.isLoggedIn === true){
    // user is logged in!
}

Nobody is forcing anybody to use the ?? operator but I think it just fits nicely together with the ?. and makes the intent clear if the developer knows how both of them work.

Collapse
sethjeffery profile image
Seth Jeffery

Probably that ?? only cares about undefined properties, not null or zero or empty string etc.

Collapse
mburszley profile image
Maximilian Burszley

It's called nullish for a reason. Because for some reason, JS thought two nulls would be a good idea.

Thread Thread
sethjeffery profile image
Seth Jeffery

May be a long argument but it's not two nulls, it's a null (defined) and an undefined. They have usefully different meanings and usages. Saying it's two nulls is a bit like saying that zero and null are the same because they both mean "nothing".

Thread Thread
jessycormier profile image
Jessy Cormier

I would have to agree with you, however in the wild most code I've seen misinterprets this and there is mixed usage of both all over the place..

Thread Thread
lampewebdev profile image
Michael "lampe" Lazarski Author

And everybody is true here :)

I try to use undefined as much as I can instead of null.

But some frameworks want you to use null.