[javascript] Finding Variable Type in JavaScript

In Java, you can use instanceOf or getClass() on a variable to find out its type.

How do I find out a variable's type in JavaScript which isn't strongly-typed?

For example, how do I know if the bar is a Boolean or a Number, or a String?

function foo(bar) {
    // what do I do here?
}

This question is related to javascript

The answer is


typeof is only good for returning the "primitive" types such as number, boolean, object, string and symbols. 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

For builtin JS types you can use:

function getTypeName(val) {
    return {}.toString.call(val).slice(8, -1);
}

Here we use 'toString' method from 'Object' class which works different than the same method of another types.

Examples:

// Primitives
getTypeName(42);        // "Number"
getTypeName("hi");      // "String"
getTypeName(true);      // "Boolean"
getTypeName(Symbol('s'))// "Symbol"
getTypeName(null);      // "Null"
getTypeName(undefined); // "Undefined"

// Non-primitives
getTypeName({});            // "Object"
getTypeName([]);            // "Array"
getTypeName(new Date);      // "Date"
getTypeName(function() {}); // "Function"
getTypeName(/a/);           // "RegExp"
getTypeName(new Error);     // "Error"

If you need a class name you can use:

instance.constructor.name

Examples:

({}).constructor.name       // "Object"
[].constructor.name         // "Array"
(new Date).constructor.name // "Date"

function MyClass() {}
let my = new MyClass();
my.constructor.name         // "MyClass"

But this feature was added in ES2015.


Here is the Complete solution.

You can also use it as a Helper class in your Projects.

_x000D_
_x000D_
"use strict";_x000D_
/**_x000D_
 * @description Util file_x000D_
 * @author Tarandeep Singh_x000D_
 * @created 2016-08-09_x000D_
 */_x000D_
_x000D_
window.Sys = {};_x000D_
_x000D_
Sys = {_x000D_
  isEmptyObject: function(val) {_x000D_
    return this.isObject(val) && Object.keys(val).length;_x000D_
  },_x000D_
  /** This Returns Object Type */_x000D_
  getType: function(val) {_x000D_
    return Object.prototype.toString.call(val);_x000D_
  },_x000D_
  /** This Checks and Return if Object is Defined */_x000D_
  isDefined: function(val) {_x000D_
    return val !== void 0 || typeof val !== 'undefined';_x000D_
  },_x000D_
  /** Run a Map on an Array **/_x000D_
  map: function(arr, fn) {_x000D_
    var res = [],_x000D_
      i = 0;_x000D_
    for (; i < arr.length; ++i) {_x000D_
      res.push(fn(arr[i], i));_x000D_
    }_x000D_
    arr = null;_x000D_
    return res;_x000D_
  },_x000D_
  /** Checks and Return if the prop is Objects own Property */_x000D_
  hasOwnProp: function(obj, val) {_x000D_
    return Object.prototype.hasOwnProperty.call(obj, val);_x000D_
  },_x000D_
  /** Extend properties from extending Object to initial Object */_x000D_
  extend: function(newObj, oldObj) {_x000D_
    if (this.isDefined(newObj) && this.isDefined(oldObj)) {_x000D_
      for (var prop in oldObj) {_x000D_
        if (this.hasOwnProp(oldObj, prop)) {_x000D_
          newObj[prop] = oldObj[prop];_x000D_
        }_x000D_
      }_x000D_
      return newObj;_x000D_
    } else {_x000D_
      return newObj || oldObj || {};_x000D_
    }_x000D_
  }_x000D_
};_x000D_
_x000D_
// This Method will create Multiple functions in the Sys object that can be used to test type of_x000D_
['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']_x000D_
.forEach(_x000D_
  function(name) {_x000D_
    Sys['is' + name] = function(obj) {_x000D_
      return toString.call(obj) == '[object ' + name + ']';_x000D_
    };_x000D_
  }_x000D_
);
_x000D_
<h1>Use the Helper JavaScript Methods..</h1>_x000D_
<code>use: if(Sys.isDefined(jQuery){console.log("O Yeah... !!");}</code>
_x000D_
_x000D_
_x000D_

For Exportable CommonJs Module or RequireJS Module....

"use strict";

/*** Helper Utils ***/

/**
 * @description Util file :: From Vault
 * @author Tarandeep Singh
 * @created 2016-08-09
 */

var Sys = {};

Sys = {
    isEmptyObject: function(val){
        return this.isObject(val) && Object.keys(val).length;
    },
    /** This Returns Object Type */
    getType: function(val){
        return Object.prototype.toString.call(val);
    },
    /** This Checks and Return if Object is Defined */
    isDefined: function(val){
        return val !== void 0 || typeof val !== 'undefined';
    },
    /** Run a Map on an Array **/
    map: function(arr,fn){
        var res = [], i=0;
        for( ; i<arr.length; ++i){
            res.push(fn(arr[i], i));
        }
        arr = null;
        return res;
    },
    /** Checks and Return if the prop is Objects own Property */
    hasOwnProp: function(obj, val){
        return Object.prototype.hasOwnProperty.call(obj, val);
    },
    /** Extend properties from extending Object to initial Object */
    extend: function(newObj, oldObj){
        if(this.isDefined(newObj) && this.isDefined(oldObj)){
            for(var prop in oldObj){
                if(this.hasOwnProp(oldObj, prop)){
                    newObj[prop] = oldObj[prop];
                }
            }
            return newObj;
        }else {
            return newObj || oldObj || {};
        }
    }
};

/**
 * This isn't Required but just makes WebStorm color Code Better :D
 * */
Sys.isObject
    = Sys.isArguments
    = Sys.isFunction
    = Sys.isString
    = Sys.isArray
    = Sys.isUndefined
    = Sys.isDate
    = Sys.isNumber
    = Sys.isRegExp
    = "";

/** This Method will create Multiple functions in the Sys object that can be used to test type of **/

['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object', 'Array', 'Undefined']
    .forEach(
        function(name) {
            Sys['is' + name] = function(obj) {
                return toString.call(obj) == '[object ' + name + ']';
            };
        }
    );


module.exports = Sys;

Currently in Use on a public git repo. Github Project

Now you can import this Sys code in a Sys.js file. then you can use this Sys object functions to find out the type of JavaScript Objects

you can also check is Object is Defined or type is Function or the Object is Empty... etc.

  • Sys.isObject
  • Sys.isArguments
  • Sys.isFunction
  • Sys.isString
  • Sys.isArray
  • Sys.isUndefined
  • Sys.isDate
  • Sys.isNumber
  • Sys.isRegExp

For Example

var m = function(){};
Sys.isObject({});
Sys.isFunction(m);
Sys.isString(m);

console.log(Sys.isDefined(jQuery));

To be a little more ECMAScript-5.1-precise than the other answers (some might say pedantic):

In JavaScript, variables (and properties) don't have types: values do. Further, there are only 6 types of values: Undefined, Null, Boolean, String, Number, and Object. (Technically, there are also 7 "specification types", but you can't store values of those types as properties of objects or values of variables--they are only used within the spec itself, to define how the language works. The values you can explicitly manipulate are of only the 6 types I listed.)

The spec uses the notation "Type(x)" when it wants to talk about "the type of x". This is only a notation used within the spec: it is not a feature of the language.

As other answers make clear, in practice you may well want to know more than the type of a value--particularly when the type is Object. Regardless, and for completeness, here is a simple JavaScript implementation of Type(x) as it is used in the spec:

function Type(x) { 
    if (x === null) {
        return 'Null';
    }

    switch (typeof x) {
    case 'undefined': return 'Undefined';
    case 'boolean'  : return 'Boolean';
    case 'number'   : return 'Number';
    case 'string'   : return 'String';
    default         : return 'Object';
    }
}

In JavaScript everything is an object

console.log(type of({}))  //Object
console.log(type of([]))  //Object

To get Real type , use this

console.log(Object.prototype.toString.call({}))   //[object Object]
console.log(Object.prototype.toString.call([]))   //[object Array]

Hope this helps


I find it frustrating that typeof is so limited. Here’s an improved version:

var realtypeof = function (obj) {
    switch (typeof(obj)) {
        // object prototypes
        case 'object':
            if (obj instanceof Array)
                return '[object Array]';
            if (obj instanceof Date)
                return '[object Date]';
            if (obj instanceof RegExp)
                return '[object regexp]';
            if (obj instanceof String)
                return '[object String]';
            if (obj instanceof Number)
                return '[object Number]';

            return 'object';
        // object literals
        default:
            return typeof(obj);
    }   
};

sample test:

realtypeof( '' ) // "string"
realtypeof( new String('') ) // "[object String]"
Object.prototype.toString.call("foo bar") //"[object String]" 

In Javascript you can do that by using the typeof function

function foo(bar){
  alert(typeof(bar));
}

Using type:

// Numbers
typeof 37                === 'number';
typeof 3.14              === 'number';
typeof Math.LN2          === 'number';
typeof Infinity          === 'number';
typeof NaN               === 'number'; // Despite being "Not-A-Number"
typeof Number(1)         === 'number'; // but never use this form!

// Strings
typeof ""                === 'string';
typeof "bla"             === 'string';
typeof (typeof 1)        === 'string'; // typeof always return a string
typeof String("abc")     === 'string'; // but never use this form!

// Booleans
typeof true              === 'boolean';
typeof false             === 'boolean';
typeof Boolean(true)     === 'boolean'; // but never use this form!

// Undefined
typeof undefined         === 'undefined';
typeof blabla            === 'undefined'; // an undefined variable

// Objects
typeof {a:1}             === 'object';
typeof [1, 2, 4]         === 'object'; // use Array.isArray or Object.prototype.toString.call to differentiate regular objects from arrays
typeof new Date()        === 'object';
typeof new Boolean(true) === 'object'; // this is confusing. Don't use!
typeof new Number(1)     === 'object'; // this is confusing. Don't use!
typeof new String("abc") === 'object';  // this is confusing. Don't use!

// Functions
typeof function(){}      === 'function';
typeof Math.sin          === 'function';