63
<script type="text/javascript">   
function saveName (firstName) {
    function capitalizeName () {
        return firstName.toUpperCase();
    }
    var capitalized = capitalizeName();console.log(capitalized instanceof String);
    return capitalized; 
}
console.log(saveName("Robert")); // Returns "ROBERT"
</script>

I want to check the type of capitalized variable, so I use capitalized instanceof String. But it shows false in console. I do not want to try capitalized instanceof Function, Object. It will take too much time.

So what is the best way to detect a variable type?

2
  • 1
    Because a string literal isn't an object of String type. See typeof capitalized Commented Jul 3, 2013 at 5:44
  • Check my small library Commented Sep 25, 2024 at 9:48

8 Answers 8

77

The best way is to use the typeof keyword.

typeof "hello" // "string"

The typeof operator maps an operand to one of eight possible values:

  • "string"
  • "number"
  • "object"
  • "function"
  • "undefined"
  • "boolean"
  • "symbol"
  • "bigint"

The instanceof method tests if the provided function's prototype is in the object's prototype chain.

This MDN article does a pretty good job of summing up JavaScript's types.

Sign up to request clarification or add additional context in comments.

5 Comments

typeof new String("hello") == "object" but it can benefit from all the same characteristics of string. It would be safest to say typeof x == "string" || x instance of String
I suppose you're correct, although in practice I almost never see new String("hello") used.
function is not a built-in type. A function is an object. And null is a type too. See ECMAScript specs, sections 8 and 11.4.3
What about array?
@SeanH Like function, array also isn't a built-in type—typeof array returns "object". However, if you want to know something is an array, you can use Array.isArray(array).
23

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

Comments

16

My favourite way is not to use typeof, because it doesn't give true type for other than boolean, string, number & function.

Instead, 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

Comments

3

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")

Comments

2

typeof capitalized == 'string'

Comments

2

The getVarType method (below) works for almost all variables. Check out this fiddle. It first uses the very fast typeof for cases where the results are reliable. Then it uses a more expensive toString method for other cases. Finally, if it is dealing with a named object (as returned by Firefox for objects like document.location) it checks for Array-like objects and reports them as arrays.

In comparison, typeof is embarrassingly poor. typeof([]) returns 'object', typeof(new Number()) returns object. It also returns 'object' for many other variables that aren't (for practical purposes) objects. See the fiddle results for a comparison.

  // Begin public utility /getVarType/
  // Returns 'Function', 'Object', 'Array',
  // 'String', 'Number', 'Null', 'Boolean', or 'Undefined'
  //
  getVarType = (function () {
    var typeof_map = {
      'undefined' : 'Undefined',
      'boolean'   : 'Boolean',
      'number'    : 'Number',
      'string'    : 'String',
      'function'  : 'Function',

      'Undefined' : 'Undefined',
      'Null'      : 'Null',
      'Boolean'   : 'Boolean',
      'Number'    : 'Number',
      'String'    : 'String',
      'Function'  : 'Function',
      'Array'     : 'Array',
      'StyleSheetList' : 'Array'
    };

    return function( data ) {
      var type, type_str;

      if ( data === null      ) { return 'Null'; }
      if ( data === undefined ) { return 'Undefined'; }

      type     = typeof( data );
      type_str = typeof_map[ type ];

      if ( type_str ) { return type_str; }

      type = {}.toString.call( data ).slice( 8, -1 );
      return typeof_map[ type ]
        || ( data instanceof Array ? 'Array' :
        ( data.propertyIsEnumerable(0) && data.length !== undefined
          ? 'Array' : 'Object' )
        );
    };
  }());
  // End public utility /getVarType/

The only possible failure mode happens if you are testing a named array that is empty (e.g. an empty enumerable DOM object besides the StyleSheetList). But on could add those to the type_of_map as needed.

I hope that helps!

Comments

1

ES-Next version with support BigInt & Symbol


"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-06-09
 * @modified
 *
 * @description js data type checker
 * @augments
 * @example
 * @link
 *
 */


const dataTypeChecker = (data, debug = false) => {
  const log = console.log;
  let result = ``;
  const typeString = Object.prototype.toString.call(data);
  result = typeString.replace(/\[object /gi, ``).replace(/\]/gi, ``);
  if(debug) {
    log(`true type`, result)
  }
  return result;
};



/*

export default dataTypeChecker;

export {
  dataTypeChecker,
};

*/

test

const dataTypeChecker = (data, debug = false) => {
  const log = console.log;
  let result = ``;
  const typeString = Object.prototype.toString.call(data);
  // const typeString = Object.prototype.toString.apply(data);
  result = typeString.replace(/\[object /gi, ``).replace(/\]/gi, ``);
  if(!debug) {
    log(`true type`, result)
  }
  return result;
};



const obj = {};
const func = () => {};


dataTypeChecker(NaN)
//"[object Number]"
dataTypeChecker(undefined)
//"[object Undefined]"
dataTypeChecker(true)
//"[object Boolean]"
dataTypeChecker({})
//"[object Object]"
dataTypeChecker(func)
//"[object Function]"
dataTypeChecker(obj)
//"[object Object]"
dataTypeChecker(Symbol())
//"[object Symbol]"
dataTypeChecker(null)
//"[object Null]"
dataTypeChecker(123)
//"[object Number]"
dataTypeChecker(BigInt(1n))
//"[object BigInt]"


// true type Number
// true type Undefined
// true type Boolean
// true type Object
// true type Function
// true type Object
// true type Symbol
// true type Null
// true type Number
// true type BigInt

Comments

0

 //-- difference constructor & typeof --//

 const fx = () => {}
 const arr = []
 const obj = {}
 
 console.log( fx.constructor == Function ) // true
 console.log( arr.constructor == Array ) // true
 console.log( arr.constructor == Object ) // false
 console.log( obj.constructor == Object ) // true
 console.log( obj.constructor == Array ) // false
 
 console.log( typeof obj ) // object
 console.log( typeof arr ) // object

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.