In Javascript, the
typeof
operator is used to retrieve the data-type of a variable or value. This can be useful for many purposes such as verifying the data-type of an argument within a function.
Basic syntax of the typeof operator
The syntax for the
typeof
operator is fairly simple, all it requires is the statement followed by the value you wish to check.
typeof value;
This will return the type of the given value in string form.
As an example let's retrieve and store the data-type of a string variable using the typeof operator:
var testString = "Hello world";
var dataType = typeof testString;
The value of the dataType variable will now be the data-type of the testString variable which would be "string".
What the typeof operator returns for different data-types
For
string
values, the typeof operator will return "string".
typeof "test"; //returns "string"
var testString = "test";
typeof testString; //returns "string"
For
integer
and
float
values, the typeof operator will return "number".
typeof 65; //returns "number"
typeof 3.14; //returns "number"
For
boolean
values, the typeof operator will return "boolean".
typeof false; //returns "boolean"
For
functions
, the typeof operator will return "function".
typeof function(){ alert("Hello") }; //returns "function"
For
arrays
and values with a Null value, the typeof operator will return "object" as these are not primitive data-types but rather objects. It will also return "object" for any other objects given.
typeof ["dog", "cat", "mouse"]; //returns "object"
typeof null; //returns "object"
var date = new Date();
typeof date; //returns "object"
For variables that have not yet been set, the typeof operator will return "undefined".
var testVariable;
typeof testVariable; //returns "undefined"
Using the typeof operator in conditions
One of the main uses of the typeof operator is verifying the data-type of a value before it is used, to do this we can compare the data-type returned by typeof to our own string containing the desired data-type. This can be very useful in functions that require a certain data-type as we can see below:
function plusTwo( inputNo ){
if( typeof inputNo === "number" ){
alert( "Your number plus two is: " + ( inputNo + 2 ) );
}
else{
alert( "Please enter a number" );
}
}
plusTwo( 2 );
plusTwo( "two" );
This function adds 2 to any given value, thus it requires the given value to be a number. The first time the function is called it will run successfully and output:
Your number plus two is: 4
The second time it runs, the condition will fail as "two" is a string and not a number, so it will output:
Please enter a number