Explain Codes LogoExplain Codes Logo

How to check if a function exists in JavaScript?

javascript
function-existence
optional-chaining
eval-safety
Anton ShumikhinbyAnton Shumikhin·Aug 23, 2024
TLDR

Use typeof to verify a function exists before execution:

if (typeof myFunc === "function") { myFunc(); }

Alternatively, with object methods, effortlessly use Optional Chaining:

me.onChange?.();

Checking function existence: Detailed Walkthrough

Spot-checking with typeof

The operator typeof is your first line of defense for checking if a value is of type function. Here's why it's crucial:

  • It's an armored tank against the dreaded ReferenceError.
  • It has brevity on its side — no need for unwieldy try-catch blocks.
  • It ensures you're not going to call an oregano plant when you need a telephone (check it's a function, not just a property).

The Optional Chaining Swiss Knife

Introduced in ES2020, Optional Chaining (?.) is like a Swiss Army knife in your code toolbox:

  • Only invokes onChange if it even exists. This lightsaber move prevents abrupt TypeError.
  • It's clean and efficient, like a well-oiled machine. Say goodbye to explicit undefined checks.

Caution: eval can burn!

In scenarios where eval is used to invoke dynamic function names, always prioritize safety:

  • Make sure the function exists using typeof before deploying your eval 🎇 fireworks.
  • Remember, the activation word is eval, but so is evil. Avoid it due to potential security concerns.

Checking property and function type in a jiffy

When dealing with nested objects or classes, your Swiss army knife includes the 'in' operator:

if ('onChange' in me) { // 'onChange' exists in the object, but is it a legit function or an imposter? if (typeof me.onChange === 'function') { me.onChange(); } }

So, not only is onChange a part of me (an existential crisis avoided!😉), but it also does what it's supposed to!

Common pitfalls and steering clear

  • Skip clumsy moves: A check for me.onChange !== 'undefined' can be replaced with a graceful typeof me.onChange === 'function' pirouette.
  • The dance of the operators: Always lead with typeof before going in with the eval move. No stepping on toes = no errors!

Good Practices to Adopt

Using standard workarounds over eval

Using eval can be like playing with fire. Instead, go for standard language constructs that JavaScript provides. It's like petting a cuddly kitten – much safer and sweeter!

Leverage thorough documentation

The Official Documentation — MDN, ECMAScript specifications — is your Knight in shining armor, always rescuing you from dragons of confusion and misinformation.

Test and Conquer

Test your code across different terrain (browsers) and weather conditions (JavaScript environments). That way, you are not surprised by rogue crocodiles or sudden tornadoes (cross-environment issues)!