Check If A Function Exists Before Calling With The typeof Operator

Published on | by
Reza Baharvand
Updated on
Image for 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.


Recent Posts

Image for Coin Flip Simulator With Javascript And CSS Animations

Coin Flip Simulator With Javascript And CSS Animations

In this tutorial, you will learn to build a small app to toss a coin using HTML, CSS, and Javascript. The possible outcomes after flipping a coin are either "Head" or "tail". The probability of getting head or tail is 50%.

Image for Use Math.PI To Calculate Area And Circumference Of A Circle

Use Math.PI To Calculate Area And Circumference Of A Circle

The "Math.PI" property returns the PI "π" constant, approximately equal to 3.14159. For example, you can calculate the circumference and surface area of a circle using "Math.PI".

Image for Create A Toggle Button In Javascript To Manipulate The DOM With The toggle() Method

Create A Toggle Button In Javascript To Manipulate The DOM With The toggle() Method

The "toggle()" is a method of the "DOMTokenList". It removes something like a "class" name from the list, and returns "false". If the "class" name does not exist, it will add it to the list and return "true".

Image for Understand The Comparison Operators In Javascript And Write Logic Like A Pro

Understand The Comparison Operators In Javascript And Write Logic Like A Pro

A comparison operator compares two values with each other, and returns a logical value such as "true" or "false". The operands can be "number", "string", "logical", or "object" values.