Optional Chaining in Javascript

dhilipkmr

Dhilip kumar

Posted on August 15, 2019

Optional Chaining in Javascript

What if I tell you that the following snippet is Possible in javascript?


const hasWorld = response && response.data && response.data.msg && response.data.msg.includes('world');

const hasWorld = response?.data?.msg?.includes('world');
Enter fullscreen mode Exit fullscreen mode

This way of checking the property of an object known as Optional Chaining.

This is currently in Stage 3 tc39, however with babel we will be able to use it in our code right now by adding the following plugin @babel/plugin-proposal-optional-chaining to your config file for babel v7+.

Below is the Transpiled Babel Code Example with Optional Chaining.

Transpiled code Example

💖 💪 🙅 🚩
dhilipkmr
Dhilip kumar

Posted on August 15, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related