Home > Article > Web Front-end > How to Check if a Variable Holds a Function in JavaScript?
How to Determine if a Variable is of Function Type
In JavaScript, variables can hold values of various types, including functions. To ascertain whether a variable contains a function, you can leverage the built-in typeof operator.
Implementation:
To construct a function that verifies if a variable is of function type:
function foo(v) { if (typeof v === 'function') { // execute specific actions } }
Usage:
Invoke the foo() function with the variable in question:
var a = function() {/* Statements */}; foo(a); // The condition will evaluate to true since 'a' is a function
Explanation:
The typeof operator returns a string indicating the type of the variable passed to it. For functions, this string is 'function'. The conditional statement evaluates to true if the variable's type is 'function', enabling you to execute custom logic accordingly.
The above is the detailed content of How to Check if a Variable Holds a Function in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!