Home >Web Front-end >JS Tutorial >Why Does `instanceof` Behave Differently with Literals in JavaScript?
Inconsistencies of instanceof with Literals
JavaScript's instanceof operator, despite its purpose of checking if an object is an instance of a class, exhibits some unexpected behavior with literals. This article dives into these inconsistencies and unveils the reasoning behind them.
Primitive Literals vs. Object Literals
Primitives, such as strings, numbers, and booleans, exist in a distinct type category compared to objects created within JavaScript. This distinction is illustrated in the following examples:
<code class="js">var color1 = new String("green"); color1 instanceof String; // returns true var color2 = "coral"; color2 instanceof String; // returns false (color2 is not a String object)</code>
While color1 is an instance of String created from a constructor, color2 is a primitive string literal.
False Returns with instanceof
Unexpectedly, instanceof returns false for many literals:
<code class="js">"foo" instanceof String // false true instanceof Boolean // false 12.21 instanceof Number // false</code>
These primitives are not considered instances of their respective wrapper objects.
Exceptions with Arrays and Objects
Array and object literals are exceptions to the rule:
<code class="js">[0,1] instanceof Array // true {0:1} instanceof Object // true</code>
They are treated as instances of the corresponding constructor functions.
Reasons for the Inconsistencies
The differing instanceof behavior is intentional. JavaScript considers primitives to be immutable values rather than objects. As such, they do not inherit from any class. The exceptions for array and object literals are made to simplify object manipulation and maintain consistency with the constructor functions.
Conclusion
Primitive literals and objects created within JavaScript differ in their behavior with the instanceof operator. This distinction can be both counterintuitive and convenient, depending on the specific use case. By understanding this nuanced behavior, developers can effectively utilize instanceof in their JavaScript code.
The above is the detailed content of Why Does `instanceof` Behave Differently with Literals in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!