Safe Navigation Operator-Optional Chaining (JS and Angular)

Safe Navigation Operator with JavaScript

The safe navigation operator, also known as Optional chaining in JavaScript is a feature that allows us to safely access properties or functions of an object without throwing an error if any of the properties in the chain are nullish (null or undefined).

The safe navigation operator was introduced in ECMAScript 2020 (ES2020) and is supported by most modern browsers.

To use the safe navigator operator, you just need to add (?.) after the object and before the property or the function needed.

Safe Navigation Operator


Safe Navigation Operator with Angular

Of course, in an Angular application, we can use the safe navigation operator with TypeScript, and we have the ability to use it with template expressions to handle null or undefined values. Here’s an example

Safe Navigation Operator in Angular Template

The safe navigation operator is implemented in the Angular compiler, in our example the Angular compiler will translate the expression into an equivalent JavaScript expression using the ternary operator to check for null or undefined values.

Code generated by Angular Compiler

When you run the ng build command,You can find the compiled JavaScript code in the main.js file located in the dist folder.

ng build --configuration development

And you can find the compiled JavaScript code for the safe navigation operator.

In our case, this is the code generated by the compiler :

angular_core__WEBPACK_IMPORTED_MODULE_1_["ɵɵtextInterpolate1"](" ", ctx.user == null ? null : ctx.user.address == null ? null : ctx.user.address.city, "");

Because it’s important to ensure that your code is concise, efficient, and easy to read. It’s recommended to use the safe navigation operator (?.) instead of relying on ngIf to check if an object is null or undefined.

Safe Navigation Operator can simplify your code, make it more robust, and reducing the risk of errors


If you have questions or comments, let me know in the comments below.

To discover more about Angular, JS and Java, you can follow me on Hashnode, Medium or Twitter.