JavaScript Data Types: Primitives, Objects, and typeof

JavaScript is dynamically typed. Variables hold no type, but the values assigned to them do, and the language checks those types at runtime. That design explains why "5" + 1 returns "51", why typeof null returns "object", and why two identical-looking objects are never equal. This guide covers the seven primitive types, the object type, the exact behavior of the typeof operator, and the edge cases that cause production bugs.

Quick Takeaways

  • JavaScript has 8 data types: seven primitives (undefined, null, boolean, number, bigint, string, symbol) and one non-primitive (object).
  • Primitives are immutable and compared by value. Objects are mutable and compared by reference.
  • typeof returns a string and is safe on undeclared variables. It has two quirks: typeof null === "object" and typeof function === "function".
  • For reliable checks, use Array.isArray(), Number.isNaN(), and Object.prototype.toString.call() instead of typeof alone.
Category Types Compared By Mutable Stored As
Primitive undefined, null, boolean, number, bigint, string, symbol Value No Value itself
Non-primitive object (arrays, functions, dates, maps, sets, plain objects) Reference Yes Reference to heap data

The 8 JavaScript Data Types

The ECMAScript specification defines eight language types. Everything else, including arrays, functions, dates, and regular expressions, is a specialized object.

Primitive Data Types

A primitive is a single, immutable value with no properties or methods of its own. JavaScript temporarily wraps primitives in objects when you call methods on them, which is why "hello".toUpperCase() works.

1. Number

The number type is a 64-bit IEEE 754 double-precision float. JavaScript has no separate integer type at the language level.

// Integers and floats share one type
const age = 30;
const price = 19.99;
const hex = 0xff;          // 255
const sci = 2.5e6;         // 2500000

// Special numeric values
console.log(1 / 0);        // Infinity
console.log(-1 / 0);       // -Infinity
console.log("abc" * 2);    // NaN

// Floating-point precision
console.log(0.1 + 0.2);                    // 0.30000000000000004
console.log(0.1 + 0.2 === 0.3);            // false
console.log(Math.abs(0.1 + 0.2 - 0.3) < Number.EPSILON); // true

The first block shows that all numeric literals produce the same type. The second shows that invalid arithmetic returns NaN instead of throwing. The third shows binary floating-point rounding: compare floats with a tolerance such as Number.EPSILON, never with ===.

NaN is the only value in JavaScript not equal to itself. Use Number.isNaN(), not the global isNaN(), which coerces its argument first.

console.log(NaN === NaN);           // false
console.log(isNaN("hello"));        // true  (coerces "hello" to NaN)
console.log(Number.isNaN("hello")); // false (no coercion)
console.log(Number.isNaN(NaN));     // true

2. BigInt

BigInt stores integers beyond the safe range of number, which is Number.MAX_SAFE_INTEGER (2^53 − 1). Append n to a literal or call BigInt().

const safe = Number.MAX_SAFE_INTEGER;       // 9007199254740991
console.log(safe + 2);                      // 9007199254740992 (wrong)

const big = BigInt(safe) + 2n;
console.log(big);                           // 9007199254740993n (correct)

// BigInt and number do not mix
// console.log(1n + 1);                     // TypeError
console.log(1n + BigInt(1));                // 2n

Past the safe limit, number silently loses precision. BigInt stays exact but throws a TypeError if you mix it with a regular number in arithmetic.

3. String

A string is an immutable sequence of UTF-16 code units. Methods never modify the original. They return a new string.

const name = "Ada";
name[0] = "E";                  // Silently ignored (throws in strict mode)
console.log(name);              // "Ada"

const upper = name.toUpperCase();
console.log(upper);             // "ADA"
console.log(name);              // "Ada" (unchanged)

// Template literals
const greeting = `Hello, ${name}!`;
console.log(greeting);          // "Hello, Ada!"

Assigning to an index does nothing in sloppy mode and throws a TypeError in strict mode. This immutability is why building large strings in a loop with += can be slower than collecting parts in an array and calling .join().

4. Boolean

A boolean is true or false. Conditions convert any value to a boolean through truthy and falsy rules. Exactly eight values are falsy: false, 0, -0, 0n, "", null, undefined, and NaN.

console.log(Boolean(""));        // false
console.log(Boolean("0"));       // true  (non-empty string)
console.log(Boolean([]));        // true  (objects are always truthy)
console.log(Boolean({}));        // true

Empty arrays and empty objects are truthy. This surprises developers who expect if ([]) to be false.

5. Undefined

undefined means a variable was declared but never assigned a value. The engine also returns it for missing properties and for functions without a return statement.

let score;
console.log(score);             // undefined

const user = { name: "Ada" };
console.log(user.email);        // undefined

function noReturn() {}
console.log(noReturn());        // undefined

6. Null

null is an intentional absence of value. You assign it on purpose. The engine never assigns it for you.

let selectedItem = null;        // Explicitly "no selection yet"

console.log(null == undefined);   // true  (loose equality)
console.log(null === undefined);  // false (strict equality)

Use null for “empty on purpose” and undefined for “not set.” Strict equality (===) separates them. Loose equality (==) treats them as equal.

7. Symbol

A symbol is a unique, immutable identifier. Every call to Symbol() returns a distinct value, even with the same description.

const id1 = Symbol("id");
const id2 = Symbol("id");
console.log(id1 === id2);       // false

const user = {
  name: "Ada",
  [id1]: 42                     // Symbol as a property key
};

console.log(Object.keys(user)); // ["name"]  (symbols are skipped)
console.log(user[id1]);         // 42

Symbols prevent property name collisions. Library authors use them to attach metadata that will not appear in Object.keys() or for...in loops.

The Object Data Type

An object is a collection of key-value pairs stored on the heap. Variables hold a reference to that location, not the data itself.

const user = {
  name: "Ada",
  roles: ["admin", "editor"],
  greet() {
    return `Hi, ${this.name}`;
  }
};

console.log(user.greet());      // "Hi, Ada"

Arrays, functions, Date, Map, Set, RegExp, and Error are all objects built on the same type.

Primitives vs. Objects: Value vs. Reference

This distinction drives most data-related bugs in JavaScript.

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

Reassigning b creates a separate value. a stays at 10.

// Objects: copied by reference
const original = { count: 1 };
const alias = original;
alias.count = 99;
console.log(original.count);    // 99 (shared reference)

Both variables point to the same heap object. A change through one is visible through the other.

// Equality compares references, not contents
console.log({ x: 1 } === { x: 1 });   // false
const ref = { x: 1 };
console.log(ref === ref);             // true

Two separate object literals occupy different memory locations, so === returns false. To copy an object independently, use structuredClone() for deep copies or the spread operator for shallow copies.

const source = { name: "Ada", tags: ["a", "b"] };

const shallow = { ...source };            // nested array still shared
const deep = structuredClone(source);     // fully independent

source.tags.push("c");
console.log(shallow.tags);                // ["a", "b", "c"]
console.log(deep.tags);                   // ["a", "b"]

The typeof Operator

typeof returns a string naming the operand’s type. It does not throw on undeclared identifiers.

console.log(typeof 42);              // "number"
console.log(typeof 42n);             // "bigint"
console.log(typeof "text");          // "string"
console.log(typeof true);            // "boolean"
console.log(typeof undefined);       // "undefined"
console.log(typeof Symbol("s"));     // "symbol"
console.log(typeof {});              // "object"
console.log(typeof [] );             // "object"
console.log(typeof function () {});  // "function"
console.log(typeof notDeclared);     // "undefined" (no ReferenceError)

typeof Results Reference Table

Value typeof Result Note
42, NaN, Infinity "number" NaN is a number
42n "bigint" Added in ES2020
"hi" "string"
true "boolean"
undefined "undefined"
null "object" Historical bug
Symbol() "symbol" Added in ES2015
{}, [], new Date() "object" Arrays are objects
function () {}, class A {} "function" Callable objects

typeof Edge Cases

The null bug. In the original JavaScript implementation, values carried a type tag, and the tag for objects was zero. null was represented as the null pointer, also zero, so it matched the object tag. The behavior stayed for backward compatibility.

console.log(typeof null);            // "object"

// Reliable null check
const value = null;
console.log(value === null);         // true

Arrays report “object”. Use Array.isArray() to detect them.

console.log(typeof []);              // "object"
console.log(Array.isArray([]));      // true
console.log(Array.isArray({}));      // false

The temporal dead zone. typeof is safe on undeclared variables, but it throws on let and const bindings accessed before their declaration.

console.log(typeof undeclaredVar);   // "undefined"

try {
  console.log(typeof early);         // ReferenceError
} catch (e) {
  console.log(e.name);               // "ReferenceError"
}
let early = 5;

A Dependable Type-Checking Helper

When typeof is too coarse, Object.prototype.toString.call() reads the internal [[Class]]-style tag and distinguishes built-in types.

/**
 * Returns a lowercase type name for any value.
 * @param {*} value
 * @returns {string}
 */
const getType = (value) =>
  Object.prototype.toString.call(value).slice(8, -1).toLowerCase();

console.log(getType(null));          // "null"
console.log(getType([]));            // "array"
console.log(getType(new Date()));    // "date"
console.log(getType(/regex/));       // "regexp"
console.log(getType(new Map()));     // "map"
console.log(getType(42n));           // "bigint"

The helper slices the [object Type] string to extract the name. It runs in O(1) time and handles every built-in, including null.

Type Coercion: Where Types Collide

JavaScript converts types implicitly in comparisons and arithmetic. The + operator concatenates when either operand is a string. Other arithmetic operators convert to numbers.

console.log("5" + 1);       // "51"  (concatenation)
console.log("5" - 1);       // 4     (numeric)
console.log(true + 1);      // 2
console.log([] + {});       // "[object Object]"
console.log("5" == 5);      // true  (loose equality coerces)
console.log("5" === 5);     // false (strict equality does not)

Default to === and !==. Loose equality applies a coercion algorithm that is hard to predict and rarely what you want.

Primitive vs. Object Comparison

Feature Primitives Objects
Memory Stack (typically), small fixed size Heap, variable size
Mutability Immutable Mutable
Equality (===) By value By reference
Copy behavior Independent copy Shared reference
Methods Via temporary wrapper Own and inherited
typeof result Matches type (except null) "object" or "function"
Garbage collection Not needed for the value itself Collected when unreachable

Best Practices and Refactoring Scenarios

Anti-pattern 1: Using typeof to Detect Arrays and null

Bad code:

function processInput(input) {
  if (typeof input === "object") {
    // Runs for null, arrays, dates, and plain objects
    return Object.keys(input);   // TypeError when input is null
  }
}

Good code:

function processInput(input) {
  if (input === null || typeof input !== "object") {
    return [];
  }
  if (Array.isArray(input)) {
    return input.map((_, i) => String(i));
  }
  return Object.keys(input);
}

The refactor rejects null first, handles arrays explicitly, and only then treats the value as a plain object.

Anti-pattern 2: Floating-Point Equality

Bad code:

if (0.1 + 0.2 === 0.3) {
  applyDiscount();   // Never runs
}

Good code:

const nearlyEqual = (a, b) => Math.abs(a - b) < Number.EPSILON;

if (nearlyEqual(0.1 + 0.2, 0.3)) {
  applyDiscount();
}

For currency, store amounts as integer cents to avoid float rounding altogether.

Anti-pattern 3: Mutating Shared Objects

Bad code:

function addTag(post, tag) {
  post.tags.push(tag);       // Mutates the caller's object
  return post;
}

Good code:

function addTag(post, tag) {
  return { ...post, tags: [...post.tags, tag] };   // New object, original untouched
}

The refactored version returns a new object, so callers holding the old reference see no surprise changes. This is the basis of predictable state in React and Redux.

Anti-pattern 4: Loose Equality and Global isNaN

Bad code:

if (value == null || isNaN(value)) { /* ... */ }

Good code:

if (value === null || value === undefined || Number.isNaN(value)) { /* ... */ }

The value == null shortcut is a known idiom that matches both null and undefined, so use it only when your team agrees on it. Replace global isNaN() with Number.isNaN() to prevent silent coercion.

Practical Checklist for Type Safety

  1. Declare with const by default and let when you must reassign.
  2. Use === for all comparisons.
  3. Validate external input (JSON, form data, API responses) at the boundary.
  4. Use Array.isArray() for arrays and === null for null.
  5. Switch to BigInt when integers can exceed Number.MAX_SAFE_INTEGER.
  6. Consider TypeScript for compile-time checking. It erases types at build time, so runtime checks still matter for untrusted data.

FAQ

How many data types does JavaScript have?

JavaScript has 8 data types. Seven are primitives: undefined, null, boolean, number, bigint, string, and symbol. The eighth is object, which includes arrays, functions, dates, maps, sets, and plain objects.

Why does typeof null return “object”?

It is a bug from the first JavaScript engine. Values carried a type tag, and null shared the tag used for objects. The behavior was kept so existing code would not break. Check for null with value === null.

What is the difference between null and undefined?

undefined means a variable has no assigned value, and the engine sets it automatically. null is a value you assign to mean “intentionally empty.” Strict equality treats them as different (null === undefined is false), and loose equality treats them as the same (null == undefined is true).

Is an array a primitive or an object in JavaScript?

An array is an object. typeof [] returns "object". To test for an array, use Array.isArray(value), which returns true only for real arrays.

Hot this week

Memory Management Across Languages: C++, Java, Python, and JavaScript

Compare manual allocation, garbage collection, and reference counting in C++, Java, Python, and JavaScript. See code and fix leaks today.

JavaScript Operators, Type Coercion, and == vs ===

Master JavaScript operators, type coercion rules, and == vs === with code examples, comparison tables, and fixes. Write safer comparisons today.

Common Python Beginner Mistakes (and How to Avoid Them)

Avoid the 10 most common Python beginner mistakes, from mutable defaults to bare except. Learn the fixes with code examples and start coding cleaner.

Dart Null Safety, Records, and Pattern Matching Explained

Master Dart 3 null safety, records, and pattern matching with production-ready code, comparison tables, and refactors. Start writing safer Dart today.

Your First Java Program: Hello World With Modern Java

Write your first Java Hello World in Java 25. Compare classic and compact versions, run code with one command, and fix common errors. Start coding now.

Topics

Memory Management Across Languages: C++, Java, Python, and JavaScript

Compare manual allocation, garbage collection, and reference counting in C++, Java, Python, and JavaScript. See code and fix leaks today.

JavaScript Operators, Type Coercion, and == vs ===

Master JavaScript operators, type coercion rules, and == vs === with code examples, comparison tables, and fixes. Write safer comparisons today.

Common Python Beginner Mistakes (and How to Avoid Them)

Avoid the 10 most common Python beginner mistakes, from mutable defaults to bare except. Learn the fixes with code examples and start coding cleaner.

Dart Null Safety, Records, and Pattern Matching Explained

Master Dart 3 null safety, records, and pattern matching with production-ready code, comparison tables, and refactors. Start writing safer Dart today.

Your First Java Program: Hello World With Modern Java

Write your first Java Hello World in Java 25. Compare classic and compact versions, run code with one command, and fix common errors. Start coding now.

std::print and std::format: Modern C++ Output

Learn std::print and std::format in C++23: syntax, format specs, custom formatters, and migration from printf and iostream. Copy the examples now.

Value Types vs Reference Types in C#: A Visual Guide

Learn how C# value types and reference types differ in memory, copying, and equality. Stack vs heap diagrams and code examples. Read the guide.

Variables in JavaScript: let, const, and Why var Is Legacy

Learn how let, const, and var differ in JavaScript: scope, hoisting, and the TDZ. See why var is legacy and refactor your code today.

Related Articles

Popular Categories