I have times in my JS code where a function may be undefined, and I want to call it only if it's defined. I write function && function()
. Is there a more concise way to do this? Something like function.callIfExists()
?
Asked
Active
Viewed 33 times
1

jonrsharpe
- 115,751
- 26
- 228
- 437

gkeenley
- 6,088
- 8
- 54
- 129
-
2You can use the optional chaining for this. `function?.()` – GmBodhi May 29 '23 at 15:42
-
2Ask yourself why a function may be undefined and rather fix that? Sounds like an unsound program structure. – deceze May 29 '23 at 15:43
-
What if it's a function param, which maybe exposed to the client? @deceze – GmBodhi May 29 '23 at 15:46
-
1https://stackoverflow.com/a/71755388/3001761 – jonrsharpe May 29 '23 at 15:46