Why it's not instanceof string?

var fruits = ['Apple', 'Banana', 'Mango']; var x = fruits.pop(); typeof x; //return string x instanceof String; //return false but fruits instanceof Array; //return true why?

4/8/2019 6:30:11 AM


2 Answers

New Answer


It's more like Instanceof operator checks whether the prototype property of the object's constructor appears in the prototype chain of your object. Which means, in most cases, that object was created by using constructor. Thus, it's safe to say that instanceof is applicable only for objects rather than primitive types. On the other hand, typeof operator tests whether the value belongs to primitive types like "string", "number", "boolean", "object", "function" or "undefined". Now, consider this: let x= "Hello" x instanceof String //false typeof x //string 'coz it's primitive type Now let's create string using constructor. let x= new String("Hello") x instanceof String //true typeof x //object


instanceof for testing object instance, cannot test primitive type. literal string is not an object, so intanceof would return false. Whereas [...] is an object of Array