JavaScript(JS) JS check if a variable is of function type

h‮:sptt‬//www.theitroad.com

In JavaScript, you can check whether a variable is of function type using the typeof operator. Here's an example:

const myFunc = function() {
  console.log('This is a function');
};

if (typeof myFunc === 'function') {
  console.log('myFunc is a function');
} else {
  console.log('myFunc is not a function');
}

In the above example, we declare a variable myFunc and assign it a function expression.

We then use the typeof operator to check whether myFunc is of function type. If it is, the code inside the if block will execute. If it isn't, the code inside the else block will execute.

Note that the typeof operator returns the string 'function' for function objects and function expressions. If you apply typeof to a function that is a method of an object or a constructor function, it will also return 'function'. However, it is important to remember that typeof null also returns 'object'. So, you should also check whether the variable is not null before checking its type.