2 min read

JavaScript Data Types

JavaScript is a dynamically typed language, meaning variables are not bound to a specific data type. You can assign a number to a variable and later assign a string to the same variable.

There are 8 basic data types in JavaScript, divided into Primitives and Reference Types.

1. Primitive Types

Primitives are immutable (cannot be changed) and stored directly by value in the stack.

  1. String: Represents textual data.
    let name = "Alice";
  2. Number: Represents both integers and floating-point numbers.
    let n = 123;
    let f = 12.345;
  3. BigInt: For integers larger than 2^53 - 1.
    let big = 9007199254740991n;
  4. Boolean: Logical true or false.
    let isActive = true;
  5. Undefined: A variable that has not been assigned a value.
    let x; // undefined
  6. Null: Represents an intentional absence of any object value.
    let y = null;
  7. Symbol (ES6): A unique and immutable identifier, often used for object property keys.
    let sym = Symbol("id");

2. Reference Types (Objects)

Reference types are mutable and stored in the heap, with a reference (pointer) stored in the stack.

  • Object: A collection of key-value pairs.
  • Array: An ordered list of values (technically a special type of object).
  • Function: A callable object.

3. The typeof Operator

The typeof operator returns a string indicating the type of the operand.

typeof undefined     // "undefined"
typeof 0             // "number"
typeof 10n           // "bigint"
typeof true          // "boolean"
typeof "foo"         // "string"
typeof Symbol("id")  // "symbol"
typeof Math          // "object"
typeof null          // "object" (This is a historical bug in JS)
typeof alert         // "function"

4. null vs undefined

  • undefined: "I don't know what this is yet." It is the default value of uninitialized variables.
  • null: "This is explicitly nothing." It is a value assigned by a programmer to indicate "no value".

programming/javascript/vanilla/javascript