Data Types & Type Checking

Difficulty: Beginner

Question

What are the different data types in JavaScript? How do you check types reliably?

Answer

JavaScript has 7 primitive types and 1 reference type. Primitives are immutable and stored by value: string, number, bigint, boolean, undefined, null, and symbol. Everything else (objects, arrays, functions, dates, regex) is a reference type stored by reference.

The typeof operator is the primary way to check types, but it has quirks. typeof null returns 'object' (a historical bug), and typeof for any function returns 'function'. For arrays and other specific objects, use Array.isArray() or instanceof.

For robust type checking, combining typeof, instanceof, and Object.prototype.toString.call() covers all edge cases. Understanding the difference between primitive values and their wrapper objects (String vs string) is also crucial.

Code examples

Primitive Types and typeof

console.log(typeof 'hello');     // string
console.log(typeof 42);          // number
console.log(typeof 42n);         // bigint
console.log(typeof true);        // boolean
console.log(typeof undefined);   // undefined
console.log(typeof Symbol('x')); // symbol
console.log(typeof null);        // object (bug!)
console.log(typeof {});          // object
console.log(typeof []);          // object
console.log(typeof function(){}); // function

typeof works for most primitives but fails for null (returns 'object') and cannot distinguish arrays from objects.

Reliable Type Checking

// Array check
console.log(Array.isArray([1, 2]));    // true
console.log(Array.isArray({length: 2})); // false

// instanceof
console.log([] instanceof Array);   // true
console.log({} instanceof Object);  // true
console.log(new Date() instanceof Date); // true

// Object.prototype.toString - most reliable
const typeOf = (val) => Object.prototype.toString.call(val).slice(8, -1);
console.log(typeOf(null));      // Null
console.log(typeOf([]));        // Array
console.log(typeOf({}));        // Object
console.log(typeOf(new Date())); // Date
console.log(typeOf(/regex/));   // RegExp

Object.prototype.toString.call() is the most reliable way to check any value's type, returning the internal [[Class]] tag.

Value vs Reference

// Primitives are copied by value
let a = 10;
let b = a;
b = 20;
console.log(a, b); // 10 20

// Objects are copied by reference
let obj1 = { name: 'Alice' };
let obj2 = obj1;
obj2.name = 'Bob';
console.log(obj1.name, obj2.name); // Bob Bob

// Equality with primitives vs references
console.log(10 === 10);           // true
console.log({} === {});            // false (different references)
console.log(obj1 === obj2);        // true (same reference)

Primitives compare by value. Objects compare by reference - two identical-looking objects are not equal unless they reference the same memory.

Key points

Concepts covered

Primitive Types, Reference Types, typeof, instanceof, Type Coercion