Question: > 
> **Possible Duplicate:**  
> 
> [Finding Variable Type in JavaScript](https://stackoverflow.com/questions/4456336/finding-variable-type-in-javascript) 
> 
> 
> 

How can I test if a value is a string or an int? Something like...

X = ?

if X is an Int {}

if X is a String {}

Thanks!

Answer: 
You can use the [typeof](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof) operator:

```
var x = 1;
console.log(typeof x);
x = 'asdf';
console.log(typeof x);

```

Prints:

```
number
string

```
Here's a function that favors `typeof`, but defaults to `Object.prototype.toString` *(which is much slower)* when needed.

This way some of those unexpected values you'll get from `new String('x')` or `null` or `/regex/` (in Chrome) are covered.

```
var type = (function () {
    var toString = Object.prototype.toString,
        typeof_res = {
            'undefined': 'undefined',
            'string': 'string',
            'number': 'number',
            'boolean': 'boolean',
            'function': 'function'
        },
        tostring_res = {
            '[object Array]': 'array',
            '[object Arguments]': 'arguments',
            '[object Function]': 'function',
            '[object RegExp]': 'regexp',
            '[object Date]': 'date',
            '[object Null]': 'null',
            '[object Error]': 'error',
            '[object Math]': 'math',
            '[object JSON]': 'json',
            '[object Number]': 'number',
            '[object String]': 'string',
            '[object Boolean]': 'boolean',
            '[object Undefined]': 'undefined'
        };
    return function type(x) {
        var the_type = typeof_res[typeof x];
        return the_type && (the_type !== 'function' || (x.apply && x.call)) ?
            the_type :
            tostring_res[toString.call(x)] || (x ? 'object' : 'null');
    };
})();

```

---

```
type( new String('test') ); // string
type( function(){} );       // function
type( null );               // null
type( /regex/ );            // regexp

```

---

**EDIT:** *I had just done a rewrite, and removed a key part of the function. Fixed.*

Or for a more compact version:

```
var type = (function() {
    var i, lc, toString = Object.prototype.toString,
        typeof_res = {},
        tostring_res = {},
        types = 'Undefined,String,Number,Boolean,Function,Array,Arguments,RegExp,Date,Null,Error,Math,JSON'.split(',');
    for (i = 0; i < types.length; i++) {
        lc = types[i].toLowerCase();
        if (i < 5) typeof_res[lc] = lc;
        tostring_res['[object ' + types[i] + ']'] = lc;
    }

    return function type(x) {
        var the_type = typeof_res[typeof x];
        return the_type && (the_type !== 'function' || (x.apply && x.call)) ? 
            the_type : 
            tostring_res[toString.call(x)] || (x ? 'object' : 'null');
    };
})();

```