+ 15
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?
2 ответов
+ 5
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
+ 5
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