To check if a function exists in JavaScript, you can use the “typeof” operator.
Example 1
function mainFunction() {
console.log('Hello, world!');
}
if (typeof mainFunction === 'function') {
mainFunction(); // Calls the function if it exists
} else {
console.log('The function does not exist.');
}
Output
In this example, typeof mainFunction will return the string ‘function’ if mainFunction is a function.
If it’s not a function or not defined, the typeof mainFunction will return a different string (e.g., ‘undefined’ or ‘object’).
By checking if typeof mainFunction === ‘function’, you can ensure that you only call the function if it exists.
If you’re working with object methods or functions in a particular namespace, you can use a similar approach.
Example 2
const mainObject = {
mainMethod: function () {
console.log('Hello, world!');
},
};
if (typeof mainObject.mainMethod === 'function') {
mainObject.mainMethod(); // Calls the method if it exists
} else {
console.log('The method does not exist.');
}
Output
In this example, the function mainMethod is a property of the mainObject object.
By checking if typeof mainObject.mainMethod === ‘function’, you can ensure that you only call the method if it exists.

Niva Shah is a Software Engineer with over eight years of experience. She has developed a strong foundation in computer science principles and a passion for problem-solving.