Taichi
Taichi

Reputation: 2587

JavaScript: Check if Object is null or undefined when getting property

I wanna do like this simply:

const someProp = someObj ? someObj.someProp : undefined;

In Ruby, we can use & operator.

some_prop = some_obj&.some_prop

Upvotes: 0

Views: 191

Answers (2)

Felix Kling
Felix Kling

Reputation: 816334

You are looking for the optional chaining operator which is also currently a stage 1 proposal:

const someProp = someObj?.someProp;

However, for the time being you could write a helper function:

function opt(obj, prop) {
  return obj ? obj.prop : null;
}

const someProp = opt(someObj, 'someProp');

Upvotes: 2

Axnyff
Axnyff

Reputation: 9944

There's no such operator currently in javascript.

There's a proposal for ?? to be added https://github.com/tc39/proposal-nullish-coalescing, but it's only at stage 1 meaning it's far from being in the language yet.

Upvotes: 1

Related Questions