JavaScript's instanceof operator returns true if an object inherits from a particular class. However, certain literals such as strings and numbers seem to defy this rule, returning false for instanceof comparisons. Why is this the case?
The key to understanding these anomalies lies in the distinction between primitives and objects. Primitives, which include strings, numbers, null, undefined, and booleans, are not created using constructors. Conversely, objects are created using constructors or object literals, like new String("foo") or {}.
For primitives, the instanceof operator returns false for all classes. This is because primitives are not instances of any class and do not inherit from any prototype. For example:
<code class="js">"foo" instanceof String // false 123 instanceof Number // false</code>
RegExp literals, despite being primitives, are an exception to this rule. They return true for instanceof RegExp. Similarly, array literals return true for instanceof Array.
Null and undefined are unique primitives that have a special behavior with instanceof. They return false for all classes, including Object. This is because they are not technically objects but instead have their own unique data types.
The inconsistencies in instanceof behavior can be confusing and lead to unexpected results. To avoid such issues, it's generally recommended to use typeof checks instead of instanceof to determine the type of a variable. For example:
<code class="js">var foo = "string"; typeof foo === "string" // true</code>
The above is the detailed content of Why Does `instanceof` Behave Differently for Primitives in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!