1

How to rewrite this in one statement:

if (foo.bar !== undefined) {
    const bee = foo.bar
}

I know there is the answer somewhere already but I can't find the right question in my mind.

1
  • What do you want to happen if it's undefined? This code would let you have anything using the variable be out of scope and not use it, but trying to put this in one statement could cause type or runtime errors. Commented Jul 11, 2020 at 12:38

2 Answers 2

2

If you have some sort of fallback value, you can use the nullish coalescing operator:

const bee = foo.bar ?? fallbackValue;
Sign up to request clarification or add additional context in comments.

Comments

0

You can try loadash npm package. But, under the hood, it does a similar check.

_.get(object, path, [defaultValue])

const bee = _.get('foo', 'bar', 'default');
const bee = _.get('foo', 'bar');

Full doc: https://lodash.com/docs/

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.