The "Elvis" Operator

The "Elvis" Operator


In many programming languages there is this special operator. Its often called "Elvis"-Operator because with a bit of imagination you can see it in the hair of Elvis. Rock´n Roll!

In other words its just a question mark (?). I encountered it while working on an Angular application. There it can be quite useful.

Why we need it?

Imagine you get some values asynchronously and want display the values in your HTML file. It works like 95% of the time but sometimes an error occured because the values that you want to display are still null because the values are not filled yet.

Its a horror scenario in a live production site because the customer will get an error and cant do nothing about it but to refresh. And if you are really, really unlucky the error occurs a second time and the user will leave the site.

The "Elvis"-Operator or also called "Safe Navigation" can catch this error.


Lets say we have an angular application where we have a "myProduct" variable that gets filled asynchronously when a user navigate to the product page. In the HTML file we only have to add the question mark, our Elvis Operator, like this: Alt Text


The "Elvis"-Operator is a cool small feature that we can use to catch some kind of errors. Sometimes its better to rewrite the code to prevent this error in the first place but sometimes you just cant do this and for this cases we can use this operator.

I hope you find this small article useful and learned something. I surely did!