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
- Use
typeoffor primitives:javascript typeof 'hello'; // 'string' typeof 42; // 'number' - Use
Array.isArray()to detect arrays becausetypeof []returns'object'. - Use
Object.prototype.toString.call(value)for precise internal class tags:javascript Object.prototype.toString.call(new Date()); // '[object Date]' - Use
instanceofto check prototype chains:javascript value instanceof Error;
Tips
typeof nullis'object'due to a historic bug; use strict equality (=== null) instead.Number.isNaN()is safer thanisNaN()because it does not coerce the value.
Common issues
typeof []andtypeof {}both return'object', so distinguish arrays withArray.isArray().- Cross-frame objects may fail
instanceofchecks; rely ontoStringtags for robust type detection.