How to Check Data Type in JavaScript: Simple Guide
In JavaScript, you can check the data type of a value using the
typeof operator for primitives and functions, Array.isArray() to detect arrays, and instanceof to check if an object is an instance of a specific class or constructor.Syntax
The main ways to check data types in JavaScript are:
typeof value: Returns a string describing the type ofvalue.Array.isArray(value): Returnstrueifvalueis an array.value instanceof Constructor: Returnstrueifvalueis created byConstructor.
javascript
typeof value Array.isArray(value) value instanceof Constructor
Example
This example shows how to use typeof, Array.isArray(), and instanceof to check different data types.
javascript
const num = 42; const text = "hello"; const arr = [1, 2, 3]; const obj = {a: 1}; const date = new Date(); console.log(typeof num); // "number" console.log(typeof text); // "string" console.log(Array.isArray(arr)); // true console.log(typeof obj); // "object" console.log(date instanceof Date); // true console.log(typeof date); // "object"
Output
number
string
true
object
true
object
Common Pitfalls
Some common mistakes when checking types in JavaScript:
typeof nullreturns"object", which is a known quirk.typeofcannot distinguish arrays from objects; useArray.isArray()instead.instanceofonly works for objects created by constructors, not primitives.
javascript
console.log(typeof null); // "object" (unexpected) console.log(typeof []); // "object" (array looks like object) console.log(Array.isArray([])); // true (correct way to check array) // instanceof with arrays console.log([] instanceof Array); // true (works but can fail across frames) // instanceof with primitives console.log(42 instanceof Number); // false console.log(new Number(42) instanceof Number); // true
Output
object
object
true
true
false
true
Quick Reference
| Method | Use Case | Example Output |
|---|---|---|
| typeof value | Check primitive types and functions | "string", "number", "boolean", "undefined", "object", "function" |
| Array.isArray(value) | Check if value is an array | true or false |
| value instanceof Constructor | Check if object is instance of a class | true or false |
Key Takeaways
Use
typeof to check basic data types like string, number, and boolean.Use
Array.isArray() to correctly identify arrays.Use
instanceof to check if an object is created by a specific constructor.Remember that
typeof null returns "object", which is a special case.Avoid relying on
typeof alone for complex types like arrays or null.