Get the data type information with typeof operator
Description
The typeof
operator tells the data type of a given variable.
It returns one of the following strings:
Returned Value | Meanings |
---|---|
"undefined" | if the value is undefined |
"boolean" | if the value is a Boolean |
"string" | if the value is a string |
"number" | if the value is a number |
"object" | if the value is an object or null |
"function" | if the value is a function |
Example
The typeof operator is called like this:
var message = "hi from java2s.com";
console.log(typeof message); //"string"
console.log(typeof(message)); //"string"
console.log(typeof 95); //"number"
console.log(typeof null);/*from www. j ava2s .c o m*/
var aString;
console.log(typeof aString);
In this example, both a variable (message) and a numeric literal are passed into the typeof
operator.
The typeof
is an operator and not a
function, no parentheses are required.
Calling typeof null
returns a value of "object"
since null
is considered to be an empty object reference.
The code above generates the following result.