DEV Community

Cover image for Optional Chaining - the null safer in javascript
William Godoy
William Godoy

Posted on

1 2

Optional Chaining - the null safer in javascript

Optional Chaining - the null safer in javascript

Sup reader!

You have probably heard something about ES2020, yeah, this is the new version of Javascript that comes with a new feature called Optional Chaining!

In Javascript, if you want to guarantee the existence of subprops, you can use two basic ways:

// By return at each verification
if (!data) {
    return
}

if (!data.user) {
    return
}

if (!data.user.name) {
    return
}

console.log('The name is:' + data.user.name)
// The name is Will
Enter fullscreen mode Exit fullscreen mode
// By return at complete verification
if (!data|| !data.user || !data.user.name) {
    return
}

console.log('The name is:' + data.user.name)
// The name is Will
Enter fullscreen mode Exit fullscreen mode

OR

const name = data && data.user && data.user.name

console.log('The name is:' + name)
// The name is Will || The name is undefined
Enter fullscreen mode Exit fullscreen mode

Perhaps the second example may seem clear to you,
but... what if u need to apply a fallback?

const name = data && data.user && data.user.name || 'William Godoy'

console.log('The name is:' + name)
// The name is Will || The name is William Godoy
Enter fullscreen mode Exit fullscreen mode

Okay... good...
enough? of course NOT!

This is where the Optional Chaining comes to save us:

const name = data && data.user && data.user.name
// turns to
const name = data?.user?.name

console.log('The name is:' + name)
// The name is Will || The name is undefined
Enter fullscreen mode Exit fullscreen mode

Amazing uh?

but you may be wondering: "If I want to add a fallback, do I do it the same way?"

there are two answers: Yes and No

let me explain, the previous way WILL work:

const name = data?.user?.name || 'William Godoy'

console.log('The name is:' + name)
// The name is Will || The name is William Godoy
Enter fullscreen mode Exit fullscreen mode

BUT prefer:

const name = data?.user?.name ?? 'William Godoy'

console.log('The name is:' + name)
Enter fullscreen mode Exit fullscreen mode

not just because the EcmaScript documentation suggest this, but for the sake of readability!

Cool so far?

so lets recap?

const data = {
    user: {
        name: 'Will',
        age: 24
    },
    status: 200
}

// Old way

const name = data && data.user && data.user.name || 'William'
// Will

// New way
const name = data?.user?.name || 'William'
// Will
Enter fullscreen mode Exit fullscreen mode

And YES, it can be use to chain functions:

const options = {
    api: {
        getData () {

        },
        // ...
    },
    // ...
}

options?.api?.getData()
Enter fullscreen mode Exit fullscreen mode

And used WITH possible callbacks:

function dbDeleteWithoutWhere(callback) {
    // Do stuffs ...
    if (callback) {
        callback()
    }
}

// OR

function dbDeleteWithoutWhere(callback) {
    // Do stuffs ...
    callback && callback()
}

// New Way

function dbDeleteWithoutWhere(callback) {
    // Do stuffs ...
    callback?.()
}
Enter fullscreen mode Exit fullscreen mode

As u can see above, if there's no callback being invoked this will not produce any errors:

// No errors after being invoked
dbDeleteWithoutWhere(undefined)

// No errors after being invoked
dbDeleteWithoutWhere(function callback() {
    // Do callback stuffs
})
Enter fullscreen mode Exit fullscreen mode

Just like functions, you can try it with arrays:

const numbers = {
    integers: [1, 2, 3, 4, 5],
    floats: [1.1, 2.1, 31.9, 45.2]
}

// Old way
const firstInteger = numbers && numbers.integers && numbers.integers[0]
// 1 || undefined

// New way
const firstInteger = numbers?.integers?.[0]
// 1 || undefined
Enter fullscreen mode Exit fullscreen mode

The optional chaining came to facilitate readability, cleanliness and help us with organization!

Thank you for reading this far!

Cheers

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️