What is the difference between...
if(myVar.constructor == String)
and
if(typeof myVar == \"string\")
The expression myVar.constructor
just returns the value of the member "constructor". It's completely possible and legal for a given object to have a constructor which points to string (or anything else). For example
function Apple() {}
var x = new Apple();
x.constructor = String
if (x.constructor == String) {
// True
}
Using the typeof
operator though provides the information you're looking for
if (typeof myVar == 'string') {
// It's a string
}
typeof
can be a little misleading. Note the following behavior:typeof
fails on real String instances:
typeof "snub"
// "string" -- as expected
typeof new String("snub")
// "object" -- even if it's still the string you're after
.constructor
consistently yields the expected result:
"snub".constructor == String
// true -- as expected
new String("snub").constructor == String
// true -- as expected
All primitive values in JavaScript have a corresponding object wrapper. It's from where primitives find a prototype chain to inherit from.
Values in JavaScript can be expressed in primitive form (specially inheriting from their respective objects), or directly in object form. It's possible some of your strings are converted into String instances along the way -- by a library perhaps -- and you won't even know it. String objects and primitives generally behave the same way. Except for with typeof
, of course.
Directly in object form -- even while the inner value may represent something that is a string, number, or otherwise -- typeof
will respond with "object"
.
.constructor
is a more reliable way to identify an object's type, and is directly available to your primitive values (like all the rest of their inherited functionality) thanks to a language feature called Autoboxing.