Data Types

Overview

Data types are classifications that tell the compiler or interpreter how the programmer intends to use the data. They determine what values a variable can hold and what operations can be performed on that data.

Core Concepts

  • Primitive Types: The most basic data types built into a language. They are usually stored by value.
    • Integer: Whole numbers (e.g., 42, -7).
    • Float/Double: Decimal numbers (e.g., 3.14).
    • Boolean: Truth values (true or false).
    • Char: Single characters (e.g., 'A').
    • String: Sequences of characters (though in some languages, strings are objects).
  • Reference Types (Composite): Types that store a reference (memory address) to the actual data stored on the heap.
    • Arrays: Collections of elements.
    • Objects/Classes: Complex structures with properties and methods.
    • Interfaces/Pointers: References to other types.
  • Static vs. Dynamic Typing:
    • Static: Types are checked at compile-time (e.g., Java, TypeScript).
    • Dynamic: Types are checked at runtime (e.g., Python, JavaScript).
  • Strong vs. Weak Typing:
    • Strong: Strict rules about mixing types (e.g., Python).
    • Weak: Implicit type conversion or “coercion” (e.g., JavaScript).

Code Examples

// TypeScript examples
let isComplete: boolean = true;      // Primitive
let count: number = 10;             // Primitive (TS uses 'number' for both int and float)
let userName: string = "Alice";     // Primitive/Special
let scores: number[] = [90, 85, 88]; // Reference (Array)

interface User { name: string }
let user: User = { name: "Bob" };    // Reference (Object)

Use Cases

  • Memory Optimization: Choosing int8 vs int64 in low-level languages to save space.
  • Type Safety: Using static typing to catch bugs before the code ever runs.
  • Data Modeling: Using objects and interfaces to represent real-world entities.

Gotchas

  • Type Coercion: In JavaScript, 1 + "2" results in "12", which can lead to subtle bugs.
  • Floating Point Precision: 0.1 + 0.2 often equals 0.30000000000000004 due to IEEE 754 binary representation.
  • Null vs Undefined: Distinguishing between a value that is explicitly “nothing” (null) and one that hasn’t been assigned yet (undefined).

Related Notes