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 ?

Community
  • 1
  • 1
Bunny Rabbit
  • 8,213
  • 16
  • 66
  • 106

2 Answers2

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"
Sean Kinsey
  • 37,689
  • 7
  • 52
  • 71
  • Exactly! instanceof would work if you explicitly called the String constructor i.e : var x = new String('myname'); – Jad May 03 '11 at 09: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
Mario Fink
  • 674
  • 4
  • 10