Why does the instanceof operator return false for some literals?
In JavaScript, the instanceof operator checks if an object is an instance of a particular class or class hierarchy. However, it behaves unexpectedly when applied to certain literals.
Literals, such as strings, numbers, and booleans, are directly defined in the code and not created through classes. Let's examine the following examples:
"foo" instanceof String //=> false "foo" instanceof Object //=> false true instanceof Boolean //=> false true instanceof Object //=> false 12.21 instanceof Number //=> false // Array and Object literals are exceptions [0,1] instanceof Array //=> true {0:1} instanceof Object //=> true
Understanding the Distinction
Primitives vs. Objects:
Instanceof and Primitives
The instanceof operator only checks if an object is an instance of a class or its descendants. Since primitives are not created through classes, instanceof will always return false for primitive literals, even if the literal's value matches the class type.
Exceptions: Array and Object
Array and Object literals are exceptions to this behavior. They are not constructed through classes but are still considered instances of the Array and Object classes, respectively. This is likely a historical quirk of the language.
Alternative Testing Method
To test if a value is of a certain primitive type, one should use the typeof operator instead of instanceof:
typeof "foo" === "string" //=> true typeof 12.21 === "number" //=> true
Conclusion
Instanceof misbehaves with primitive literals because they are not instances of any class. Array and Object literals are exceptions because of a historical quirk. When determining the type of a primitive, it is advisable to use typeof instead of instanceof.
The above is the detailed content of Why Does `instanceof` Return `false` for Literals in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!