To check if a variable is a function in JavaScript, you can use the typeof
operator.
Here’s an example:
function exampleFunction() {
// function code goes here
}
if (typeof exampleFunction === 'function') {
console.log('exampleFunction is a function!');
}
Code language: JavaScript (javascript)
The typeof
operator returns the type of a variable or expression. In this case, it will return 'function'
if the variable is a function.
Alternatively, you can use the isFunction()
method from the underscore.js
library, which is a utility library for JavaScript.
Here’s an example:
function exampleFunction() {
// function code goes here
}
if (_.isFunction(exampleFunction)) {
console.log('exampleFunction is a function!');
}
Code language: JavaScript (javascript)
The isFunction()
method returns true
if the argument is a function, and false
otherwise. It’s a convenient way to check if a variable is a function without using the typeof
operator.
Leave a Reply