In this post, we will discuss about typeof operator in javascript. First we should know what is typeof.
What is typeof:
typeof is an operator that is used to identify the type of any object in javascript. It returns a value that is string. So you can compare any string value from returned value of typeof.
// Examples
typeof 12; // number";
typeof false or typeof true; // "boolean"
typeof undefined; // "undefined"
typeof {}; // "object"
// Call with parentheses
typeof(12); // "number";
In the above code, you can see we have used typeof in two ways.
typeof is an operand and not a function and the second method it is not actually a function call. The operation in parenthesis is evaluated then passed to typeof.
When to use typeof:
typeof can be used if you want to check some variable that is undefined or not. If you are using any undefined variable into your code, you can get a ReferenceError. By using typeof into your code can prevent you from this error.
if( typeof foo !== "undefined") {
// defined
}else {
// undefined
}
This is how you can use typeof in your code. :)
0 Comment(s)