How to Check if a Variable is of Function Type

There are several methods in JavaScript that can check whether a variable is of function or not. Let’s discuss each of them and find the fastest solution to the question.

The typeof Operator

You can use the typeof operator to check the variable. It returns a string which indicates the type of the unevaluated operand.

console.log(typeof '' === 'string'); 
console.log(typeof function() {} === 'function');   
console.log(typeof true === 'boolean'); 
console.log(typeof Symbol() === 'symbol'); 
console.log(typeof {key: 1} === 'object');

The instanceof Operator

Another method can be the instanceof operator which checks the type of an object at run time. It return a corresponding boolean value, for example, either true or false to indicate if the object is of a particular type or not:

let str = new String(); 
let date = new Date();
console.log(str instanceof Object); 
console.log(str instanceof Date); 
console.log(str instanceof String); 
console.log(str instanceof Number); 
console.log(date instanceof Date); 
console.log(date instanceof Object); 
console.log(date instanceof String); 
console.log(date instanceof Number);
The typeof method appears to be the fastest in Chrome, but in Firefox the instanceof method is the winner.

The toString() Method

Another useful method is toString(). Each object has a toString() method, which is called when a value of string type is expected. If the method is not overridden, it will return the object type.

let arr = new Array("Html", "Css", "Javascript", "Git");        
let str = arr.toString();
console.log("Showing string is : " + str );

JavaScript Functions

JavaScript functions are the main blocks of code that are designed to perform a particular task. Functions allow the code to be called many times without repetition. Variables that are defined inside a function cannot be accessed from anywhere outside that function, as it is defined only in the scope of the function.


Do you find this helpful?

Related articles