Explain Codes LogoExplain Codes Logo

Why does instanceof return false for some literals?

javascript
instanceof
javascript-types
type-checking
Alex KataevbyAlex Kataev·Oct 5, 2024
TLDR

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.

console.log(1 instanceof Number); // false - "I'm not a number, I'm a free man!" (said the 1) console.log(typeof 1 === 'number'); // true - "I am number '1'" console.log('text' instanceof String); // false - "I'm just a string along" console.log(new String('text') instanceof String); // true - "Now I'm a real boy!" (said the Pinocchio string)

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:

console.log([] instanceof Array); // true - Empty but not lonely! console.log(function(){} instanceof Function); // true - "I've got potential!" (said this ambitious, empty function)

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:

console.log(Object.prototype.toString.call([])); // [object Array] - "It’s what’s on the inside that matters!" console.log(Object.prototype.toString.call(/regex/)); // [object RegExp] - "Regex - No strings attached!"

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:

let str1 = 'text'; let str2 = new String('text'); console.log(str1 === str2); // false - "I may be text, but I'm not THAT text!" console.log(str1 == str2); // true - "Yeah, same pinch!"

A fair warning: Primitives vs Objects

Though quirky and flexible, JavaScript demands clarity, especially when juggling between primitives and their object forms.

let name = 'Jane'; name.last = 'Doe'; console.log(name.last); // undefined - 'Jane' says, "Last? What last? I only know 'Doe'"