PUBLISHED ON: FEBRUARY 24, 2023
JavaScript Program to Check If a Variable is of Function Type
This tutorial will teach how to make a JavaScript Program to Check If a Variable is of Function Type. To understand this article we need to have a decent knowledge of JavaScript typeof operator, Function call(), and JavaScript Object toString(). It's an easy job that can be done with a few lines of code. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
1. Program to Check If a Variable is of Function Type Using instanceof Operator
In the program given below, the instanceof
operator is used to check the variable type. The instanceof
operator tests to see if the prototype
property of a constructor appears anywhere in the prototype chain of an object.
The return value is a boolean value.
// JavaScript Program to check if a variable is of function type
function testVari(variable) {
if(variable instanceof Function)
console.log('The variable is of function type');
else
console.log('The variable is not of function type');
}
const count = true;
const x = function() {
console.log('Hello JavaScript')
};
testVari(count);
testVari(x);
The variable is not of function type
The variable is of function type
2. Program to Check If a Variable is of Function Type Using typeof Operator
In the program given below, the typeof
operator is used with strict equal to ===
the operator to check the type of variable. The typeof
operator returns a string indicating the type of the operand's value. The typeof
operator gives the variable data type. ===
checks if the variable is equal in terms of value and data type.
// program to check if a variable is of function type
function testVar(variable) {
if(typeof variable === 'function')
console.log('The variable is of function type');
else
console.log('The variable is not of function type');
}
const count = true;
const x = function() {
console.log('Hello JavaScript! JavaScript is the programming language of the Web.')
};
testVar(count);
testVar(x);
The variable is not of function type
The variable is of function type
Conclusion
In conclusion, it is essential for any programmer to be familiar with the JavaScript data types. In this blog, we've discussed how to recognize and distinguish between various data types. However, as JavaScript is a dynamically typed language, the data type of a variable can change at runtime.