JavaScript typeof operator
The JavaScript typeof operator is used to return a string that represents the type of JavaScript for a given value. It returns the data type of the operand in the form of a string. The operand can be a literal or a data structure like a function, an object, or a variable.
Syntax
There are following two ways of using the typeof operator.
Values
operand: It is an expression that represents the object or primitive whose type is to be returned.
The possible return values of the typeof operator are tabulated as follows:
Type of the operand | Result |
---|---|
object | “object” |
number | “number” |
string | “string” |
boolean | “boolean” |
function | “function” |
undefined | “undefined” |
Let’s understand this operator by using some examples.
Example1
In this example, the operands are of number type. The typeof operator will print the “number” as the type of the operand, whether the operand is a negative interger, floating-point number, infinity, NaN, zero, or any integer.
Output
After the execution of the above code, the output will be –
number number number number number number
Example2
In this example, the operands are of string type. The typeof operator will print the “string” as the type of the operand, whether the operand is an empty string, collection of characters, number written in quotes.
Output
After the execution of the above code, the output will be –
string string string string string
Example3
In this example, the operands are of Boolean type. The typeof operator will print the “boolean”, as the type of the operand, if the operand is true, or false.
Output
After the execution of the above code, the output will be –
boolean boolean boolean
Example4
In this example, the operands are of undefined type. The typeof operator will print the “undefined” as the type of the operand. Here, the type of Null is undefined, it is because it is written as Null instead of null. If we write it as null, the type of it will be object.
Output
After the execution of the above code, the output will be –
undefined undefined undefined
Example5
In this example, the operands are of Object and Function type. The typeof operator will print the “object” and “function”, according to the type of the operand.
Output
After the execution of the above code, the output will be –
object object object object function function