0
0
JavascriptHow-ToBeginner · 3 min read

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 of value.
  • Array.isArray(value): Returns true if value is an array.
  • value instanceof Constructor: Returns true if value is created by Constructor.
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 null returns "object", which is a known quirk.
  • typeof cannot distinguish arrays from objects; use Array.isArray() instead.
  • instanceof only 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

MethodUse CaseExample Output
typeof valueCheck primitive types and functions"string", "number", "boolean", "undefined", "object", "function"
Array.isArray(value)Check if value is an arraytrue or false
value instanceof ConstructorCheck if object is instance of a classtrue 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.