Home > Web Front-end > JS Tutorial > body text

Why Does `instanceof` Return `false` for Literals in JavaScript?

DDD
Release: 2024-11-03 22:39:31
Original
771 people have browsed it

Why Does `instanceof` Return `false` for Literals in JavaScript?

The Mystery of Instanceof and Literals

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
Copy after login

Understanding the Distinction

Primitives vs. Objects:

  • Literals, such as strings, numbers, and booleans, are primitives. They exist independently of any class or instance.
  • Objects, such as arrays and objects created with the new keyword, are instances of classes.

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template