Borislav Hadzhiev
Sat Oct 30 2021·1 min read
Photo by freestocks
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.
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.
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.
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.
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.