How to check data types in JavaScript accurately

· Category: JavaScript

Short answer

Use typeof for primitives, instanceof for custom objects, and Object.prototype.toString.call() for a precise type tag when typeof is insufficient.

Steps

  1. Use typeof for primitives: javascript typeof 'hello'; // 'string' typeof 42; // 'number'
  2. Use Array.isArray() to detect arrays because typeof [] returns 'object'.
  3. Use Object.prototype.toString.call(value) for precise internal class tags: javascript Object.prototype.toString.call(new Date()); // '[object Date]'
  4. Use instanceof to check prototype chains: javascript value instanceof Error;

Tips

  • typeof null is 'object' due to a historic bug; use strict equality (=== null) instead.
  • Number.isNaN() is safer than isNaN() because it does not coerce the value.

Common issues

  • typeof [] and typeof {} both return 'object', so distinguish arrays with Array.isArray().
  • Cross-frame objects may fail instanceof checks; rely on toString tags for robust type detection.