Type detection
It is a way by which we can identify the type of data. We know that data types can be three types. So if we are working on data sometimes we need to identify the datatype of particular data. So in JavaScript, we have a typeof operator to identify the type of data. According to MDN.
“The typeof operator returns a string indicating the type of the unevaluated operand.”
typeof undefined // "undefined"
typeof 0 // "number"
typeof true // "boolean"
typeof "foo" // "string"
typeof {} // "object"
typeof null // "object"
typeof function(){} // "function"
typeof NaN // "number"
Now you can see typeof operator works fine for primitive data type, undefined and function. So How we can get the correct type of array, object, or null?
Constructor property approach
Now for this, we can use the constructor property every variable has it’s own constructor property by which we can find the constructor function of that variable. If you don’t know about the constructor or constructor property then I will explain my upcoming tutorial. Let’s see how it works –
var num = 2;
console.log(num.constructor == Number); // true
var str = "test";
console.log(str.constructor == String); // true
var bol = true;
console.log(bol.constructor == Boolean); // true
var arr = [];
console.log(arr.constructor == Array); // true
var obj = {};
console.log(obj.constructor == Object); // true
var vNull = null;
console.log(vNull.constructor ); // Uncaught TypeError
var vUndefined;
console.log(vUndefined .constructor ); // Uncaught TypeError
This way also works fine for all. But again it fails on the special types. For null and undefined it will throw Uncaught TypeError. So now we can use this approach.
Object.prototype.toString method approach
This approach works fine for all types of data. Let’s see how it works. Now I am creating a function for finding data type –
// It will return typeof data
function getType(val) {
return Object.prototype.toString.call(val).match(/\[object (\w+)\]/)[1];
}
console.log(getType(null)); // Null
console.log(getType(undefined)); // Undefined
console.log(getType({})); // Object console.log(getType([])); // Array
Now you can see this function work properly for all kind of data but it will fail when you have created a class-like structure in javascript. Like
var Fun = function () {};
var f = new Fun();
console.log(getType(f)); // Object
But here you can see I just want my constructor here (Fun).
The instanceof operator
So if you want to get a proper result here you need instanceof operator. The instanceof allows us to check if the object is created by its own constructor: Let’s see how to use this –
console.log(f instanceof Fun); // true