Check type of variable is of function

How can I check if a JavaScript variable is function type?

In this tutorial, we will learn different approaches to checking if a JavaScript variable is of function type or not. In JavaScript, the function contains the block of code, making the code reusability better.

There are mainly two ways to declare the functions, one is a named function, and another is an anonymous function. While declaring the anonymous function, we need to store it in some variable to access it from somewhere in our code or call that function.

Here, users can see how to declare the anonymous function and store it into the variable.

let tutorialspoint = function() < //code for the function>

As you can see in the above example, the ‘tutorialspoint’ variable contains the function and sometimes programmers need to check if it is a type of function or not.

To solve the above problem, we can use the below different methods.

  • Using the typeof operator
  • Using the instanceof operator
  • Using the object.prototype.toString method

Using the typeof operator

Using the typeof operator in JavaScript, we can determine the data type of any variable. It returns the value of the data type of its operand in the string format.

Here, we can use the string equality ‘===’ operator in JavaScript to compare the returned value with the ‘function’ string. If the returned value matches with the ‘function,’ the variable is of the function type.

Users can follow the below syntax for the typeof operator.

Syntax

typeof operand typeof(operand)

Parameter

  • operand − It can be any object or variable for which we want to check if it is a type of function or not.

Return − the value of the data type of ‘operand‘ in the string format.

Example 1

The below example demonstrates how to use of the typeof operator to check the variable is of the function type.

     

typeof Operator: Check if a variable is of function type.

let a = 10; let b = 20; var tutorialsPoint = function () < return a + b; >; // function to check type of variable is function or not function checkTypeOfVar() < if (typeof tutorialsPoint === 'function') < document.write("
The type of tutorialsPoint variable is function." ); > else < document.write("The type of tutorialsPoint variable is not a function."); > > document.getElementById("result").innerHTML = "var tutorialsPoint = " + tutorialsPoint; // call the function checkTypeOfVar();

In the above code, users can see that the typeof tutorialsPoint returns the ‘function,’ and control of the function goes to the ‘if’ block and gives the above output.

Читайте также:  Способ разметки гипертекста html

Using the instanceof operator

The ‘instanceof’ operator helps us to determine whether any variable is of a given type or not. It takes two operands, one variable and another data type, object, function, or any with which you want to compare the current variable type.

In our case, we will take a function as the operand as we want to check variable is of function type or not. It returns the Boolean value, and it returns true if the type of the variable match with the given type; otherwise, it returns false.

Syntax

variable instanceof datatype

In the above syntax, as a datatype we will take ‘Function’ as we need to verify whether the variable type is function or not. It returns true if the variable is of the Function type.

Example 2

In the below example, we are checking the function type of variable using the instanceof operator.

     

instanceof Operator: check if a variable is of function type.

let a = 10; let b = 20; var multiply = function () < return a * b; // other code for the function >; // function to check type of variable is function or not function checkTypeOfVar() < let isTypeOfFunction = multiply instanceof Function; if (isTypeOfFunction===true) < document.write("
The type of multiply variable is function."); > else < document.write("
The type of multiply variable is not a function."); > > document.getElementById("result").innerHTML = "var multiply = " + multiply ; // call the function checkTypeOfVar();

In the above code, users can see that instanceof multiply Function returns the “true” and control of the function goes to the ‘if’ block and it prints the above output.

Using the object.prototype.toString method

Generally, the object.prototype.toString method is called automatically for every object when an object needs to return the string in JavaScript. Also, we can override the return value for the toString method if we don’t override the default return for the object.toString() method is ‘[Object Type]’ where type is the object type.

Here, we will check if it returns the ‘Function’ type or not.

The standard syntax to get the type of any object or variable is as follows.

Syntax

Object.prototype.toString.call(Object_Name) == '[ object Function]'

In the above syntax, we have to pass variable in the place of Object_Name to check if it is of function type or not.

Parameter

Example 3

In the below example, we get the type of the variable using the Object.prototype.toString method.

    

object.prototype.toString() Methodd

let a = 10; let b = 20; var substract = function () < return a - b; // other code for the function >; // function to check type of variable is function or not function checkTypeOfVar() < // get the type of tutorialsPoint variable let typeOfVar = Object.prototype.toString.call( substract ); // compare typeOfVar with the funciton type if (typeOfVar == '[object Function]') < document.write("
The type of substract variable is function."); > else < document.write("
The type of substract variable is not a function."); > > document.getElementById("result").innerHTML = "var substract = " + substract ; // call the function checkTypeOfVar();

In the above code, users can see that Object.prototype.toString.call(subtract) method returns the “[object Function]”. So, it prints the above output.

Читайте также:  Плетение питон и кобра

Conclusion

We have seen a total of three ways to check whether the variable is an instance of the function or not in this tutorial. Users can use any of the approaches according to their comfortability. The first and second approach has straightforward syntax to find the variable type, so maybe users can go for that before using the third approach.

Источник

Check if a variable is of function type or not

A JavaScript function is a block of code designed to perform a particular task. It is executed when it is invoked(when something calls it). A function can be either a named or an anonymous one. This article talks about how to go about checking whether a variable is of ‘Function’ type or not. Before we understand the different methods of implementing this and also why anyone would want to assign a function to a variable let’s look at how named and anonymous functions are declared.

Table of Contents

Function declaration types

Named Function declaration

This function has a named identifier associated with it which can be used to invoke the function

function functionName(parameter1, paramter2) < //code>

Anonymous Function declaration

It is a function that is declared without any named identifier to refer to it.

Advantage of assigning a function to a variable

Assigning a function to a variable allows us to pass this variable as a parameter to another function. This is particularly useful in scenarios that require runtime flexibility. You would mainly use such functions to run a load of code in response to an event firing For example, a button being clicked using an event handler.

myButton.onclick = function() < //response actions >

Code

Using instanceof operator

The instanceof operator is used to check the type of objects at run time. This operator returns a Boolean value(true or false). In the example below, an IF statement is used to check if the type of parameter passed to checkFunction() is of Function type or not.

//javascript check if function-Using instanceof operator < script >// Declare a variable and initialize it // Declare a variable and initialize it with an anonymous function var exampleVar = function() < /* A set of statements */ >; // to check a variable is of function type or not function checkFunction(x) < if (x instanceof Function) < document.write("Variable is of function type"); >else < document.write("Variable is not of function type"); >> // Function call checkFunction(exampleVar); < /script>

Using Strict Equality comparison (===) along with typeof operator

In JavaScript, strict equality comparison (===) Operator is used to check whether two entities are of not only equal values but also of equal type. The typeof operator returns a string which indicates the type of the unevaluated operand. Both of these operators provide a Boolean result. This result can be compared using the IF statement to check if the object type is «Function’.

//javascript check if function-Using Strict Equality comparison (===) along with typeof operator  

Using object.prototype.toString

This method uses object.prototype.toString. Every object has a toString() method, which returns ‘[object type]’ where ‘type’ is the object type. An IF statement can be used to compare if the returned value is of the type ‘Function’.

//javascript check if function-Using object.prototype.toString  

Caveats

In Chrome typeof(obj) === ‘function’ appears to be the fastest; however, in Firefox obj instanceof Function is performs relatively better.

Читайте также:  Html таблица всех команд

Источник

How to check if a JavaScript variable is a function or not.

This is a simple guide on how to check if a JavaScript variable is a function or not. As you probably already know, JavaScript allows you to create and assign functions to variables. This makes it possible to pass functions as parameters to other functions.

Let’s jump right in and take a look at the following code snippet, which includes a custom function that checks to see whether a given variable is a function or not:

//Create a JS function and assign it to a variable //called «func» var func = function()< //Print to the browser console. console.log('Hello! I am a function!'); >; //Create a simple JS string for example purposes. var str = ‘I am not a function!’; //Our custom function, which checks to see if a variable //is a function or not. function isFunction(variableToCheck) < //If our variable is an instance of "Function" if (variableToCheck instanceof Function) < return true; >return false; > //Check to see if our JavaScript variable «func» is a function. if(isFunction(func)) < //If it is, print to console and call the function. console.log('func is a function!'); func(); >else < console.log('func is not a function!'); >//Check to see if our JavaScript variable «str» is a function. if(isFunction(str)) < //If it is, print to console and call the function. console.log('str is a function!'); str(); >else

  1. We create two different variables – a function type variable and a string type variable.
  2. We create a custom function called isFunction, which checks to see if a JS variable is of type “function” or not. This returns TRUE or FALSE.
  3. We then test both of our variables and log the results to the console.

Best of all, the custom function above will even work in old browsers such as Internet Explorer 6!

Hopefully, you found this guide to be helpful!

Источник

Оцените статью