Check if Variable is of Function Type using JavaScript

avatar

Borislav Hadzhiev

Sat Oct 30 20211 min read

banner

Photo by freestocks

Check if Variable is of Function Type #

To check if a variable is of type function, use the typeof operator, e.g. typeof myVariable === 'function'. The typeof operator returns a string that indicates the type of the value. If the type of the variable is a function, a string containing the word function is returned.

index.js
function sum(a, b) { return a + b; } if (typeof sum === 'function') { console.log('โœ… type is function'); } else { console.log('โ›”๏ธ type is NOT function'); }

We used the typeof operator to check if a variable has a type of function.

The typeof operator returns a string that indicates the type of value to the right hand side. Here are some examples.

index.js
console.log(typeof (() => {})); // ๐Ÿ‘‰๏ธ "function" console.log(typeof function () {}); // ๐Ÿ‘‰๏ธ "function" console.log(typeof null); // ๐Ÿ‘‰๏ธ "object" console.log(typeof []); // ๐Ÿ‘‰๏ธ "object" console.log(typeof {}); // ๐Ÿ‘‰๏ธ "object" console.log(typeof ''); // ๐Ÿ‘‰๏ธ "string" console.log(typeof 0); // ๐Ÿ‘‰๏ธ "number"

For both arrow functions and named functions, the typeof operator returns a string containing the word function.

The typeof operator works in the same way when used with async functions.

index.js
console.log(typeof (async () => {})); // ๐Ÿ‘‰๏ธ "function" console.log(typeof async function () {}); // ๐Ÿ‘‰๏ธ "function"

Even if you use it with a variable that's not declared, you wouldn't get an error.

index.js
if (typeof sum === 'function') { console.log('โœ… type is function'); } else { console.log('โ›”๏ธ type is NOT function'); }

In this example, we checked for the type of the sum variable, which is not declared.

The typeof operator returned "undefined" and didn't throw an error.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee