Chapter III · Data Types

Data Types Overview

JavaScript categorizes values into distinct data types, split between lightweight primitives and complex objects.

01 What are Data Types?

Every value in JavaScript belongs to a specific data type. These types inform the engine how much memory to allocate and what operations can safely be performed on the data.

JavaScript is dynamically typed, meaning variables are not bound to any single data type. A variable can hold a number at one moment and a string the next.

02 Simple Example

Using the typeof operator to inspect the data type of various values.

types.js
console.log(typeof 42);          // "number"
console.log(typeof "hello");     // "string"
console.log(typeof true);        // "boolean"
console.log(typeof {});          // "object"

The typeof operator inspects the underlying value currently referenced by an expression.

03 How It Works

JavaScript classifies types into two primary categories: seven primitive types (which hold single, immutable values) and the Object type (which holds collections of key-value pairs or structured data).

JavaScript Data Types (7 Primitives + 1 Object) Primitives (Immutable) string, number, bigint, boolean, undefined, null, symbol Objects (Mutable) Objects, Arrays, Functions, Dates, Maps

JavaScript divides data into immutable primitive types and mutable reference object types.

04 Step-by-Step

  1. A value is created in code.

  2. The engine assigns internal type metadata to the value representation.

  3. Operators and methods verify type compatibility during execution.

05 Mental Model

"Data types are customs checkpoints at the border, ensuring cargo matches permitted categories."

They prevent illegal operations, like multiplying text strings as if they were raw numbers.

06 Interview Questions

Q: Is typeof null === 'object' a bug?

Yes, a famous and permanent one — it's a bug from JavaScript's first implementation in 1995 that can't be fixed without breaking the web, so it remains part of the spec.

Q: How would you reliably check if a value is an array?

Array.isArray(value) — typeof returns 'object' for arrays too, so it can't distinguish them.

Key Takeaway

Data types classify JavaScript values into primitives and objects, dictating how memory is allocated and manipulated.

Related Concepts