2

If I have an object like this

 const obj = {
     func: props.func, // we don't know if func is a function or undefined...
 }

and I have this in my code:

 obj.func(params);

What is the good way to execute the optional function of the object?

I have thought to do something like this:

if(typeof obj.func === "function")
   obj.func(params);

or

try {
    obj.func(params);
} catch (err) {}

But I'm not sure if both forms are correct to do it (or if there is a better way) as I don't have much experience with javascript.

Someone who knows? Thank you.

Conchi Bermejo
  • 283
  • 2
  • 14

2 Answers2

-1

Read about optional chaining in JS here

Personally, I would use this way from ES2020:

const props = {
  func: Math.random() >= 0.5 ? undefined : (params) => console.log(params),
};

const obj = {
   func: props.func,
};

And then

obj.func?.("hello world!");

This way is recommended here

Victor Molina
  • 2,353
  • 2
  • 19
  • 49
-1

I personally would go with

if (typeof obj.func === "function") {
    obj.func();
}

because if you use a try catch, and an error occurred within the function itself, it might appear as though the function was never called in the first place.

Simon
  • 369
  • 1
  • 9