Trivia Questions1 min readPremium

Explain type coercion using typeof, instanceof, and Object.prototype.toString.

 

Demystifying Type Coercion in JavaScript

Type coercion in JavaScript involves the automatic or implicit conversion of values from one data type to another. Understanding the mechanisms for type checking, such as typeof, instanceof, and Object.prototype.toString(), is crucial for managing and predicting the outcomes of such conversions. MDN documents typeof and instanceof in detail.

Using typeof

The typeof operator returns a string indicating the data type of its operand. It’s straightforward for simple data types but has its quirks. For example, typeof null returns "object", which can be misleading, and it does not distinguish between arrays, objects, or null, all returning "object".

// Examples of typeof
console.log(typeof 42); // "number"
console.log(typeof "JavaScript"); // "string"
console.log(typeof null); // "object"

Employing instanceof

The instanceof operator checks whether an object is an instance of a specific constructor or its prototype chain. It’s useful for custom objects and built-in types like Array, but doesn’t apply to primitive data types.

// Examples of instanceof
console.log([] instanceof Array); // true
console.log({} instanceof Object); // true

Utilizing Object.prototype.toString()

The Object.prototype.toString() method returns a standardized string representation of an object’s type. It’s a more reliable way to determine types, especially for objects, arrays, and null values,... premium content.

Premium

Keep reading with Premium

Get the rest of this guide plus every premium question, solution, and system design deep dive.

  • All premium solutions
  • System design deep dives
  • Company-specific prep

4.9/5 from our users