0

similar question in Java: Java: check for null or allow exception handling

related:How to deep check for "null" or "undefined" with JS?

assuming a.foo() is a well-tested function that returns either

undefined or an object with a function such as {bar:()=>log('baz')},

hence, it would seem logical to write

a.foo().bar()

which obviously won't work.

(the undefined is the result of an empty return; when no information can be delivered)

Should

1. The operation be tried,

try{a.foo().bar();}catch(e){}

2. a new variable be declared

const u = a.foo();
if(u) u.bar();

3. or foo() return {bar:()=>{}} instead of undefined?

so that

a.foo().bar();

can be written normally?

what is the industry standard? what is fastest?

3
  • It is a personal opinion on what to do, there is no right answer. Commented Sep 23, 2017 at 2:12
  • what is the industry standard? what is fastest? Commented Sep 23, 2017 at 2:27
  • There is no standard. I can tell you no one would use try catch Commented Sep 23, 2017 at 2:28

1 Answer 1

0

As already commented, this is a personal opinion and I would also stick to it that most people would try to avoid the try-catch story...

But anyway I wanted to add that you can also simply check:

a.foo() && a.foo().bar()

in case a.foo() will return undefined, then the right side wont be executed and thus this expression return undefined.

On the other side, if a.foo() is not undefined than the right side will be executed and this expression will evaluate to the result of a.foo().bar()

Sign up to request clarification or add additional context in comments.

2 Comments

but that is bad because you are calling the method twice. If it is expensive it is not wise. If it is just a static property, that is a way to do it.
in that case, just assign a.foo() to a variable and substitute a.foo() with the variable name. Than you call it just once as in a try-catch

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.