Skip to main content

How to Check if a Function is Defined in JavaScript

Before you can safely call a function in JavaScript, you often need to check if it has been defined and is available to be called. Attempting to invoke a variable that is not a function will result in a TypeError, which can crash your application. The most reliable and direct way to perform this check is with the typeof operator.

This guide will teach you how to use the typeof operator to reliably check if a variable holds a function, and explain why it is superior to other methods like instanceof.

The typeof operator is the definitive tool for this job. It returns a string indicating the type of the unevaluated operand. When used on a function, it returns the string "function".

For example, you have a variable and need to confirm that it is a function before you try to call it.

// Problem: How to safely check if `myFunction` is callable?
function myFunction() {
return 'Hello!';
}

const myVariable = 123;

Solution:

function myFunction() {
return 'Hello!';
}

// Check a valid function
if (typeof myFunction === 'function') {
console.log('myFunction is a defined function.');
myFunction(); // Safe to call
} else {
console.log('myFunction is NOT a function.');
}
// Output: myFunction is a defined function.

// Check a non-function variable
if (typeof myVariable === 'function') {
// This block will not run
} else {
console.log('myVariable is NOT a function.');
}
// Output: myVariable is NOT a function.

Output:

myFunction is a defined function.
myVariable is NOT a function.

How typeof Works with Undefined Variables

A key advantage of the typeof operator is that it is safe to use on a variable that has not been declared. Instead of throwing a ReferenceError, it will simply return the string "undefined".

// `nonExistentFunction` has not been declared anywhere.
if (typeof nonExistentFunction === 'function') {
// This block will not run
} else {
console.log('nonExistentFunction is not defined.');
}
// Output: nonExistentFunction is not defined.

Output:

nonExistentFunction is not defined.
note

This makes typeof a very robust tool for checking for the existence and type of a function in a single step.

An Alternative Method: The instanceof Operator

You can also use the instanceof operator to check if a variable is an instance of the Function constructor.

function myFunction() {
return 'Hello!';
}

if (myFunction instanceof Function) {
console.log('myFunction is an instance of Function.');
}

Output:

myFunction is an instance of Function.
note

While this works for most cases, it has some edge cases and is generally not preferred over typeof.

Why typeof is the Best Practice

typeof is the superior method for checking for functions for two main reasons:

  1. Safety with Undeclared Variables: As shown above, typeof does not throw a ReferenceError for variables that don't exist. instanceof will throw an error in this case.
    // ⛔️ ReferenceError: nonExistent is not defined
    if (nonExistent instanceof Function) {}
  2. Cross-Realm Reliability: In complex environments with multiple frames (like <iframe>s), each frame has its own global scope and its own Function constructor. An instanceof Function check will fail if the function was created in a different frame, but typeof will work correctly.

For these reasons, typeof is the most reliable and professional choice.

Practical Example: Optional Callback Functions

A perfect use case for this check is in a function that accepts an optional callback. The function should only attempt to call the callback if one was actually provided.

function performAsyncTask(data, onCompleteCallback) {
console.log('Performing a task with data:', data);

// Simulate a delay
setTimeout(() => {
console.log('Task finished.');

// Check if the callback is a function before calling it
if (typeof onCompleteCallback === 'function') {
onCompleteCallback({ success: true });
}
}, 1000);
}

// Example 1: Calling WITH a callback
performAsyncTask({ id: 123 }, (response) => {
console.log('Callback executed!', response);
});

// Example 2: Calling WITHOUT a callback (no error is thrown)
performAsyncTask({ id: 456 });

Conclusion

For checking if a variable is a defined function in JavaScript, the choice is clear.

  • The typeof variable === 'function' check is the recommended best practice. It is the safest, most reliable, and most idiomatic way to verify that a variable holds a function before you attempt to call it.
  • Avoid using instanceof Function, as it is less safe with undeclared variables and can fail in multi-frame environments.

By using typeof for your function checks, you can write more robust, error-proof code.