drinovc drinovc - 5 months ago 20
Javascript Question

Is there a JavaScript undefined property handling like in Angular2 templates

I was wondering if there is a neat way of doing this:

if (app && app.object && app.object.foo) {
alert(app.object.foo.bar);
}


This is really long and "ugly".

I found out that Angular2 has something really great for cases like this. But I think it's only for templates:

<div>{{this?.object?.foo?.bar}}</div>


This got me really exited because I have a lot of code that looks just like the first example. It get's the job done but I'm really hopping there is something more sophisticated.

Answer

Many languages have this functionality, some call it safe navigation operator or even Elvis operator (yes haha).

JavaScript does not have this functionality. If you are open to use CoffeeScript, you might take a look at the existential operator.

But, if you want to keep with JS, you should take a look at lodash.get(), which lets you do something like this:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// → 3

_.get(object, 'a.b.d.c', 'default');
// → 'default'
Comments