Explain how memory is allocated for primitives compared to objects in JavaScript.

In JavaScript, memory is allocated differently for primitives compared to objects.

Memory Allocation for Primitives:

Primitives are Stored by Value:
  - When you declare a primitive variable (such as a number, string, boolean, etc.), the actual value of the primitive is stored directly in the memory location associated with that variable.
  - Each variable holds its own copy of the data, and modifications to one variable do not affect other variables.

Independent Memory Locations:
  - Primitive values are independent of each other in memory. If you have two variables with primitive values, they are stored in separate memory locations, and changes to one variable do not impact the other.

Example:


let num1 = 10;   // Memory location A
let num2 = num1; // Memory location B (copying the value of num1)


In the example above, `num1` and `num2` each have their own memory locations, and changing the value of one doesn't affect the other.

Memory Allocation for Objects:

Objects are Stored by Reference:
  - When you declare an object variable, the memory stores a reference (address) to the actual object rather than the object itself.
  - Multiple variables can reference the same object in memory.

Shared Memory Locations:
  - Objects are shared by reference. If you have two variables referencing the same object, modifications to the object through one variable will be reflected when accessing the object through the other variable.

Example:

let obj1 = { key: "value" }; // Memory location X
let obj2 = obj1;             // Both obj1 and obj2 reference the same object in memory (location X)


In the example above, both `obj1` and `obj2` reference the same object in memory. Changes to the object (like adding or modifying properties) through one variable will be visible when accessing the object through the other variable.

Understanding these memory allocation differences is crucial for managing data in JavaScript, particularly when dealing with mutability and the sharing of values between variables.