JavaScript check if function exists: is an important checkpoint to avoid undefined errors and stops running your rest of the code. This type of checking is required to avoid errors, ensure backward compatibility, and allow you to execute code only if the function exists in your code.
In my article, I am going to share how you can check a JS function’s existence more precisely with code examples and best practices. I will also demonstrate how you can even check object methods. So keep reading and enjoy.
JavaScript provides a few different ways to see if a function exists. I will teach you the most common and best practices.
Table of Contents
#1: Using typeof Operator
The typeof operator is a reliable way to check the type of a variable or expression. Therefore, we can check a JS function’s existence by using this typeof operator. Here is a more detailed example:
<script>
// Define a function
function myFunction() {
console.log('myFunction() exists!');
}
// Check if the function exists
if (typeof myFunction === 'function') {
myFunction(); // This will run if the function exists
} else {
console.log('myFunction() does not exist.');
}
// Did not define function myFunctionNotExist
if (typeof myFunctionNotExist === 'function') {
myFunctionNotExist();
} else {
console.log('myFunctionNotExist() does not exist.');
}
// JavaScript Check if Function Exists
// Check the return value of typeof operator
console.log(typeof myFunction);
console.log(typeof myFunctionNotExist);
</script>
Output
Check the output carefully. What have we learned from the above example? We learned – the JS typeof operator returns “function” if the function exists in your code; otherwise, return “undefined”.
#2: Using window object
As a JS developer, we knew that a window object holds our every reference (methods/functions) and value type (variables) within the window or a web page. So if we check the window object, we can easily determine a function’s existence.
Let’s say you want to test a function named “myFunction” within the window object, then we can write the JS code in the below way:
<script>
// Define a function
function myFunction() {
console.log('myFunction(): function exists!');
}
// Check if the function exists
// Return function object
if (window.myFunction) {
myFunction();
} else {
console.log('myFunction(): function does not exist.');
}
// Not define myFunctionNotExist before
// hence return undefined
if (window.myFunctionNotExist) {
myFunctionNotExist(); // check failed
} else {
console.log('myFunctionNotExist(): function does not exist.');
}
// JavaScript check if function exists
// check directly by if condition
// If not exist then throw an error
// so use window object instead
if(myFunction)
console.log('myFunction(): function exists!');
// Check the return value of window object
console.log(window.myFunction); //print the whole function
console.log(window.myFunctionNotExist);
</script>
Output
#3: Using the in Operator – Check if a function exists within an object
Another way to check if a function exists in an object is by using the in operator. This operator checks if a property exists in an object:
<script>
// Define an object
let myObject = {
myMethod: "a variable"
};
// Check if the method exists in the object
if ('myMethod' in myObject) {
//myObject.myMethod(); // This will run if the method exists
console.log('Method exist');
} else {
console.log('Method does not exist.');
}
</script>
It shows “Method exist”. However, myMethod is a variable not a function. This is the similar issue with window object. Let’s try to resolve it by combining typeOf operator.
<script>
// Define an object
let myObject = {
myMethod: "a variable",
myMethod: function() {
console.log('Method exists!');
}
};
// Check if the method exists in the object
if ('myMethod' in myObject && typeof myObject.myMethod === 'function') {
myObject.myMethod(); // This will run if the method exists
} else {
console.log('Method does not exist.');
}
</script>
Output
#4: Using the hasOwnProperty Method
If you want to check a function within an object, you can also choose the most common object property hasOwnProperty like this:
<script>
// Define an object
let myObject = {
myMethod: function() {
console.log('Method exists within an object!');
}
};
// Check if method exists within an object
if (myObject.hasOwnProperty('myMethod')) {
myObject.myMethod(); // This will run if the method exists
} else {
console.log('Method does not exist.');
}
</script>
#5: Using a try…catch Block
If you are not concerned about standard coding, then you can call the function within a try catch block. If the function exists, then there is no issue, but if the function does not exist, then the code will throw an error and will handle it by a catch block. Your code won’t stop running other codes. But we don’t recommend it.
<script>
try{
myMethod(); // method invoked but throw error
}
catch(err){
// JavaScript Check if Function Exists - Failed
console.log('myMethod() does not exist: '+err)
}
</script>
Output
Best practices – JavaScript check if function exists
- Use typeOf: It’s standard, very effective, and solves your issues for almost every case.
- Check Object Methods Carefully: Ensure that the property is a function. How to do that? Again, use the typeOf operator.
- Provide Fallbacks: It’s a good programming practice to have a fallback or throw a notImplementedException error in case the function does not exist.
Full example – Demonstrating best practices
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript check if function exists</title>
</head>
<body>
<script>
// Function definition
function myFunction() {
console.log('Function exists!');
}
// Object with method
let myObject = {
myMethod: function() {
console.log('Method exists!');
}
};
// Check if function exists
if (typeof myFunction === 'function') {
myFunction();
} else {
console.log('Function does not exist.');
}
// JavaScript Check if Function Exists
// Check if method exists in object
if ('myMethod' in myObject && typeof myObject.myMethod === 'function') {
myObject.myMethod();
} else {
console.log('Method does not exist.');
}
</script>
</body>
</html>
JS Methods code example
Method | Code Example |
---|---|
typeof Operator | typeof myFunction === ‘function’ |
window object | if (window.myFunction) |
The in Operator | if (‘myMethod’ in myObject) |
The hasOwnProperty Method | if (myObject.hasOwnProperty(‘myMethod’)) |
The try…catch Block | try{ myMethod(); } catch(err){ …. } |
Conclusion
I am very confident that by following the examples and best practices, you can effectively check if a function exists in JavaScript or not. This practice will help you to create robust and error-free code, ensuring a smoother user experience and maintaining compatibility across different environments. I hope you are now comfortable with JavaScript Check if Function Exists all code examples.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply