JavaScript Data Types and Memory Storage - anastasiamexa/react-complete-guide-course-resources GitHub Wiki

Primitive Values

Primitive values in JavaScript are immutable, meaning their values cannot be changed after creation. They are directly stored in the variable's memory space. Examples of primitive data types include:

  • Number: Represents numeric values.
    let num = 42;
    
  • String: Represents textual data.
    let str = "Hello, World!";
    
  • Boolean: Represents logical values (true or false).
    let isTrue = true;
    
  • Null: Represents intentional absence of any object value.
    let nullValue = null;
    
  • Undefined: Represents uninitialized variables or missing function arguments.
    let undefinedValue = undefined;
    
  • Symbol: Represents unique identifiers.
    let sym = Symbol('mySymbol');
    

Reference Values

Reference values in JavaScript are mutable, allowing their state to be changed after creation. They are stored as references to objects in memory. Examples of reference data types include:

  • Object Literal:
    let person = {
      name: 'John',
      age: 30
    };
    
  • Array:
    let numbers = [1, 2, 3, 4, 5];
    
  • Function:
    function sayHello() {
      console.log('Hello, World!');
    }
    

Memory Storage

Primitive Values

Primitive values are stored directly in the variable's memory space. When you copy or pass a primitive value, a new copy of the value is created.

let a = 10;
let b = a; // 'b' gets a copy of the value 10.
b = 20;    // Changing 'b' does not affect 'a'.

Reference Values

Reference values are stored as references to objects in memory. When you copy or pass a reference value, you are working with a reference to the object in memory.

let arr1 = [1, 2, 3];
let arr2 = arr1; // 'arr2' references the same array as 'arr1'.
arr2.push(4);    // Modifying 'arr2' also modifies the underlying array.

console.log(arr1); // Output: [1, 2, 3, 4]
console.log(arr2); // Output: [1, 2, 3, 4]

Stack and Heap

  • Stack: Used for storing primitive values and references to objects. Actual values of primitives are stored, while references to objects are stored.

  • Heap: Used for storing the actual objects (arrays, objects, functions). Reference variables on the stack hold the memory address pointing to the location of the object in the heap.

let num = 42;      // 'num' stores the value 42 on the stack.
let obj = { prop: "value" };  // 'obj' stores a reference to an object in the heap.