Why does instanceof return false for some literals?
Primitives in JavaScript like 1 or 'text' aren't instances of an object, hence instanceof gives false because this operator is designed to inspect object's prototype. To handle primitives, use the typeof operator instead. Also, if desired, you could wrap these literals in their corresponding object constructor, so the instanceof can be utilized.
Mastering literals, prototypes, and type-check woes in JavaScript
Let's dive deeper into understanding the behavior of literals, prototypes, and the instanceof operator in JavaScript.
Primitives and their encounter with typeof
In JavaScript, primitives are basic data types (string, number, boolean, null, undefined, symbol, bigint). Being non-object entities, typeof is your best bet for them.
Object constructors' role with instanceof
Occasionally there could be scenarios where you'd want your primitives posing as objects. Use new with the appropriate constructor (String, Number, Boolean) to create an object instance, enabling instanceof to be used.
instanceof and arrays, functions
Arrays and Functions - our dear buddies in JavaScript are structural types. The instanceof operator gets along famously with them:
null and undefined - the rebels
Alright, show of hands. Who left null and undefined from the party? Since both don't have corresponding constructor objects, instanceof gives them a cold shoulder and returns false.
Deep-dive into types with Object.prototype.toString
When regular type checking isn't enough, call upon Object.prototype.toString to do the heavy lifting. This method helps access the internal [[Class]] property, providing us with details that typeof would usually withhold:
Plain JavaScript - Frills and fanciness aside
JavaScript is part chameleon, part magician. This jestster can shape-shift its types, throw curveballs but, once tamed, prove helpful to the very end.
Trust, but verify
Regardless of the browser, instanceof behaves consistently with primitives. Stay vigilant, though, and confirm from official docs and community-approved resources.
Odd couple: Primitives and their Object form
Primitives are immutable loners, compared by value. Objects are their mutable, extrovert counterparts, compared by reference. This contrast can lead to some humorous misunderstandings:
A fair warning: Primitives vs Objects
Though quirky and flexible, JavaScript demands clarity, especially when juggling between primitives and their object forms.
Was this article helpful?