1

Possible Duplicate:
how to detect if variable is a string

x = 'myname';
x.intanceOf == String

why does the second statement returns false ? how can i check if a variable is string or not ?

0

2 Answers 2

4

It is false because intanceOf[sic] is undefined, not a reference to the String constructor.

instanceOf is an operator, not an instance method or property, and is used like this:

 "string" instanceof String

But this will return false as the literal string is not a String object created using the String constructor.

So what you really want to do is use the type operator

typeof "string" == "string"
1
  • Exactly! instanceof would work if you explicitly called the String constructor i.e : var x = new String('myname');
    – Jad
    May 3, 2011 at 9:23
1

Using instanceOf might not be a good idea after all.

The typeof operator (together with instanceof) is probably the biggest design flaw of JavaScript, as it is near of being completely broken.

See: http://bonsaiden.github.com/JavaScript-Garden/#types.typeof

Instead use Object.prototype.toString like so:

function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

is('String', 'test'); // true
is('String', new String('test')); // true

Not the answer you're looking for? Browse other questions tagged or ask your own question.