JavaScript typeof operator
One of the JavaScript’s coolest functionality is to check the which type of object you have, It is helpful to you run time check which type of object this is and perform the according task on the object.
The typeof operator returns the string of evaluated object which indicates the which type of object this is.
Syntax
typeof <variable name or value>
Type | Result |
---|---|
Number | number |
String | string |
Boolean | boolean |
Object | object |
Function | function |
Undefined | undefined |
Null | object |
var thisString = "String"; var thisNumber = 123; var thisBoolean = false; var thisFunction = function () { } var thisUndefined; console.log("String Variable: " + typeof thisString); console.log("Number Variable: " + typeof thisNumber); console.log("Boolean Variable: " + typeof thisBoolean); console.log("Function : " + typeof thisFunction); console.log("Null " + typeof null); console.log("Undefined: " + typeof thisUndefined);
Now run this script on you browser and checks the output on the browser’s console you will get the string returned by the typeof operator. You will get output like this:
Note: null keyword is also the object when you are checking any variable which currently null than it also return you the object. So it better you to check any object using the instanceof operator so it will return name of the class of that object.
alert(typeof null == "object"); // returns true
Some examples code:
//Numbers typeof 13 === "number"; typeof NaN === "number"; //String typeof "JavaScript" === "string"; typeof "" === "string"; //Boolean typeof true === "boolean"; typeof false === "boolean"; //Object typeof null === "object"; typeof { a: "a"} === "object"; // It is also called the plain object typeof [4, 5, 6] === "object"; typeof new Date() === "object"; //Functions typeof function () { } === "function";
see the instanceof operator
Happy Coding. 🙂