Duke Dougal
Duke Dougal

Reputation: 26336

In ES2015 is there a way to directly access object properties without checking for undefined?

In ES5 whenever I want to get some property I need to first check that it exists like this:

if (typeof floob.flib !== 'undefined') {
    // do something
}

even worse is that for nested properties you have to manually check for the existence of every property down the dotted path.

Is there a better way to do this in ES2015?

Upvotes: 0

Views: 203

Answers (3)

choz
choz

Reputation: 17868

By using typeof,

typeof floob.flib === 'undefined'

equals to,

floob.flib === undefined

I assume you want to check whether floob.flib has a value, and if it does, you want to perform an operation with it.

However, in JS, there's almost simpler way to achieve this.

E.g.

if (floob.flib) {
   // 'floob.flib' is NOT 'null', 'empty string', '0', false or 'undefined'
}

This also works well if you want to assign variable with ternary ( ?: ) operators.

var str = floob.flib ? 'exists' : 'does not exist';

Or even using logical OR ( || )

var str = floob.flib || '<= either null, empty, false, 0 or undefined';

Note that unless floob.flib does not produce ReferenceError exception, the code above should work just fine.

Upvotes: -1

darthtrevino
darthtrevino

Reputation: 2235

If you have lodash available, you can use _.get(obj, path, defaultValue) (https://lodash.com/docs#get)

Upvotes: 2

zerkms
zerkms

Reputation: 254944

  1. If it is just a single depth property name - you don't need typeof, you may just compare the value with undefined.

  2. Your solution is prone to false negatives: it may think there is no a property with a given name, while there is one. Example: var o = { foo: undefined };

  3. If you need to check if the path exists in the nested objects - you still need to implement recursion/loop/or use any library that does either for you.

  4. ES2015 did not bring anything new to solve this problem easier.

Upvotes: 2

Related Questions