0

I wanna do like this simply:

const someProp = someObj ? someObj.someProp : undefined;

In Ruby, we can use & operator.

some_prop = some_obj&.some_prop
3

2 Answers 2

2

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');
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.