How do I check if a value is a function in JavaScript?
Richard W
richard w profile pic

In JavaScript, there are several ways to check if a value is a function. Here are some common methods: 1. Using thetypeof operator: - Thetypeof operator returns a string indicating the data type of a value. When applied to a function, it returns'function'.

1
2
3
4
5
6

   const value = someFunction;
   if (typeof value === 'function') {
     // value is a function
   }
   

In this example, thetypeof value === 'function' condition is used to check ifvalue is a function. 2. Using theinstanceof operator: - Theinstanceof operator checks if an object is an instance of a specific constructor function. When applied to a function, it returnstrue.

1
2
3
4
5
6

   const value = someFunction;
   if (value instanceof Function) {
     // value is a function
   }
   

Here, thevalue instanceof Function condition is used to determine ifvalue is a function. 3. Using theObject.prototype.toString() method: - TheObject.prototype.toString() method returns a string representing the object's type. When called on a function, it returns'[object Function]'.

1
2
3
4
5
6

   const value = someFunction;
   if (Object.prototype.toString.call(value) === '[object Function]') {
     // value is a function
   }
   

In this example,Object.prototype.toString.call(value) === '[object Function]' is used to check ifvalue is a function. 4. Using theFunction.prototype properties: - All functions in JavaScript inherit from theFunction constructor, so you can also check if a value is a function by accessing the properties on theFunction.prototype.

1
2
3
4
5
6

   const value = someFunction;
   if (value instanceof Function || typeof value === 'function' || value.constructor === Function) {
     // value is a function
   }
   

In this case, the condition checks ifvalue is an instance ofFunction, if its type is'function', or if its constructor isFunction. Choose the method that best suits your needs. Thetypeof operator andinstanceof operator are commonly used and sufficient for most scenarios. TheObject.prototype.toString() method provides a more explicit check, while checking theFunction.prototype properties allows for additional customization.