Wield the Unholy Power of JavaScript Optional Chaining in VS Code!

A Not-So-Spooky Introduction

The hair on my arms and legs stood up. A single tear rolled down my cheek. My voice shook as I uttered under my breath, “Impossible.” Was it some kind of spooktacular Halloween fright I beheld in my gaze? A ghoul, perhaps? No! These were goosebumps of joy. Tears of triumph. Tremors of delight. Ladies and gentlemen, I’m of course talking about optional chaining syntax becoming available in VS Code!

Why should you care? Because optional chaining rips. And you’re worth it.

What is optional chaining?

Have you ever done this?

console.log(person && person.location && person.location.city);

Or this?

if (onError) {

onError(error.message);

}

Doing checks for potentially undefined or null values like this unnecessarily clutters up your code and stresses out your mother. Is that what you want? She’s worried sick. Give her a call and tell her all about how much cleaner your code is going to be with optional chaining. This feature permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

What’s the Syntax?

You can now implement the above examples like this:

console.log(person?.location?.city);

If any of the values in the chain of properties is undefined or null , then instead of a TypeError being thrown, undefined will be logged to the console!

onError?.(err.message);

Here’s a little bonus treat for you. You can use optional chaining for potentially undefined functions! This is especially useful for callbacks. If onError is undefined or null , nothing happens! Your mother would be proud.

The (Only Sorta) Bad News

As of today, no native environment supports this feature. It’s in TC39 Stage 3, meaning it’s likely to be accepted into JavaScript in the future, but you can use it today thanks to this Babel plugin. The great news is that VSCode now won’t complain about this syntax if you have the JavaScript and TypeScript Nightly extension installed.

Now get out there and write some code, you absolute minx. ❤️