Chooce video playback speed
speed:1

Enable optional chaining in Node app by using Babel

InstructorShruti Kapoor

Share this video with your friends

Send Tweet

Optional chaining enables safe access of properties of an object. It can be enabled in a Node app by using Babel preset-env.

This lesson is a Community Resource

A Community Resource means that it’s free to access for all. The instructor of this lesson requested it to be open to the public.

Instructor: In a Node app, we can access Object Properties using dot notation in JavaScript. However, if a property's parent doesn't exist, JavaScript will throw an error. To safeguard ourselves in case of accessing members of non-existent properties, we can use Optional Chaining.

Optional Chaining is stage 4 ECMAScript proposal. In a Node app, we can use Optional Chaining by using Babel. Babel's environment preset allows us to use latest JavaScript features in Node.

We'll first install @babel/preset-env core Node in CLI modules. Then, we will enable Babel by letting it compile our JavaScript, and point our npm start script to run the compiled JavaScript. We'll also enable a preset right here.

In our Node app, let's access a property that doesn't exist by using optional chaining. As we can see, the result is undefined, which means we are set to use optional chaining in Node app. To ensure that Babel is working correctly, we can also access a property that exists, and the result is 7, as we expected.