what is the best way to check variable type in javascript

2021+ one liner answer.

My favourite way is not to use typeof

Why? because it doesn't give true type for other than boolean,string,number & function.

Then what? Here is small utility function using Object.prototype 🤩

var trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()

Results:

trueTypeOf([]); // array
trueTypeOf({}); // object
trueTypeOf(''); // string
trueTypeOf(new Date()); // date
trueTypeOf(1); // number
trueTypeOf(function () {}); // function
trueTypeOf(/test/i); // regexp
trueTypeOf(true); // boolean
trueTypeOf(null); // null
trueTypeOf(); // undefined

The best way is using typeof

typeof "blahha" 

I made a function with help of jQuery library code, jQuery library type method github link .

var getType = (function() {

    var objToString = ({}).toString ,
        typeMap     = {},
        types = [ 
          "Boolean", 
          "Number", 
          "String",                
          "Function", 
          "Array", 
          "Date",
          "RegExp", 
          "Object", 
          "Error"
        ];

    for ( var i = 0; i < types.length ; i++ ){
        typeMap[ "[object " + types[i] + "]" ] = types[i].toLowerCase();
    };    

    return function( obj ){
        if ( obj == null ) {
            return String( obj );
        }
        // Support: Safari <= 5.1 (functionish RegExp)
        return typeof obj === "object" || typeof obj === "function" ?
            typeMap[ objToString.call(obj) ] || "object" :
            typeof obj;
    }
}());

You can call it as getType("Hello")


The best way is to use the typeof keyword.

typeof "hello" // "string"

The typeof operator maps an operand to one of six values: "string", "number", "object", "function", "undefined" and "boolean". The instanceof method tests if the provided function's prototype is in the object's prototype chain.

This Wikibooks article along with this MDN articles does a pretty good job of summing up JavaScript's types.


use typeof();

example:

> typeof "foo"
"string"
> typeof true
"boolean"
> typeof 42
"number"

So you can do:

if(typeof bar === 'string') {
   //whatever
}

Keep in mind that, typeof is only good for returning the "primitive" types, number, boolean, object, string. You can also use instanceof to test if an object is of a specific type.

function MyObj(prop) {
  this.prop = prop;
}

var obj = new MyObj(10);

console.log(obj instanceof MyObj && obj instanceof Object); // outputs true

Tags:

Javascript