How to Check if a Function Exists in JavaScript
Table of Contents
Because JavaScript is a loosely-typed language, it can sometimes be unclear what type a variable is.
In the case of functions, if you call a function that is non-existent, you will get an error.
To avoid this, you can check if the function exists before calling it.
In this post, we'll learn how you can check if a function exists before calling it in JavaScript.
Checking if a function exists in JavaScript
First, let's define a simple function:
JAVASCRIPTconst greeting =(name => {
console.log(`Hello ${name}`);
}
We know this is a function because we can call it:
JAVASCRIPTconst greeting = name => {
console.log(`Hello ${name}`);
}
greeting("John");
BASHHello John
However, what if we want to check if the function exists before calling it?
To do this, you can try using the typeof
operator:
JAVASCRIPTconst greeting = name => {
console.log(`Hello ${name}`);
}
if (typeof greeting === "function") {
console.log("This is a valid function")
}
BASHThis is a valid function
Another alternative you could do is simply try calling the function anyways but wrapping it in a try-catch block to catch any potential exceptions that might be thrown:
JAVASCRIPTconst greeting = name => {
console.log(`Hello ${name}`);
}
try {
greeting("John");
} catch (error) {
console.log(error)
}
BASHHello John
If the function was not valid, an error would get printed to the console but the script would continue executing.
Conclusion
In this post, we learned how to check if a function exists in JavaScript.
Simply use the typeof
operator or try calling the function within a try-catch block for safety.
Thanks for reading!
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up Stylus CSS Preprocessor