JavaScript Type Detection

Type detection

It is a way by which we can identify the type of data. We know that data type can be three type. So if we are working on data sometime we need to identify datatype of particular data. So in javascript we have 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, null.

Constructor property approach
Now for this we can use 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’s work –

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 working fine for all. But again it’s fail on special type. 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 type of data. Let’s see how it’s work. Now i am creating function for finding data type –

// It will return typeof data
function getType(val) {
return\[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 creating 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 to check if the object is created by it’s own constructor: Let’s see how to use this –

console.log(f instanceof Fun); // true

You May Also Like

About the Author: Pankaj Bisht