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

```
[`typeof`](https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/typeof) does the trick *most* of the time. But if your `Number` or `String` is not a primitive, it will return `'object'`. Generally, that is not what you want.

```
var str = new String('Hello');
typeof str; // 'object'

```

`typeof` also says that `null` is an `'object'` and in WebKit, a regex is a `'function'`. I think the main advantage of `typeof` is to check for a variable without throwing a `ReferenceError`.

You can check a variable's `constructor` property too, or use `variable instanceof String`. However, both of these don't work in a multiple `window` environment when using cross `window` code.

The other *guaranteed* way of determining the type is with...

```
var getType = function(variable) {
    return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
}

```

[jsFiddle](http://jsfiddle.net/Xug86/).