Skip to content

Check If A Function Exists Before Calling With The typeof Operator

Check If A Function Exists Before Calling With The typeof Operator

Introduction

If you are sharing scripts from different modules or you have a large codebase, you can use the typeof operator to check if a function exists.

What Does typeof Operator Do?

The typeof operator returns the type of the given operand. It could return any of the following:

  • "function"
  • “undefined”
  • “object”
  • “boolean”
  • “number”
  • “bigint”
  • “string”
  • “symbol”

You can see what typeof returns in the example below:

typeof Math.floor === "function";
typeof 37 === "number";
typeof "Just a string" === "string";
typeof { name: "Reza Baharvand" } === "object";
typeof true === "boolean";
typeof Symbol() === "symbol";

You can see the Math.floor returns a function. If you want to learn more about Math.floor() function, read this article.

Writing A Function To Check If The function() Exists

You can check if a function exists in your code by using the following code:

// Random function that increments a number by 2
function addTwo(num) {
  return num + 2;
}

// function to check if another function exists
function funcExists(func) {
  if (typeof func === "function") {
    console.log("Function exists");
  }
}

funcExists(addTwo);
// Function exists

funcExists(anotherFunction);
// ReferenceError: anotherFunction is not defined

The funcExists() function returns "Function exists" if the provided argument is a function, otherwise it throws a reference error.