Understanding how reference values are stored in memory is crucial for any frontend developer, especially when working with JavaScript and its data types. In JavaScript, values can be categorized into two types: primitive values and reference values. While primitive values (like numbers, strings, and booleans) are stored directly in the memory stack, reference values (like objects, arrays, and functions) are stored differently, which can lead to some interesting behaviors in your code.
Reference values are stored in the heap memory, and what you actually manipulate in your code is a reference to that memory location rather than the value itself. This distinction is important for understanding how data is passed around in your applications.
When you create a reference value, such as an object or an array, JavaScript allocates memory for that value in the heap. The variable you use to reference that value holds a pointer to the location in memory where the actual data is stored. This means that if you assign an object to another variable, both variables will point to the same memory location.
let obj1 = { name: 'Alice' };
let obj2 = obj1; // obj2 now references the same object as obj1
obj2.name = 'Bob'; // Modifying obj2 also modifies obj1
console.log(obj1.name); // Outputs: Bob
In the example above, both `obj1` and `obj2` point to the same object in memory. When we change the `name` property through `obj2`, it also affects `obj1`, demonstrating that they reference the same memory location.
let obj1 = { name: 'Alice', address: { city: 'Wonderland' } };
let obj2 = { ...obj1 }; // Shallow copy
obj2.address.city = 'New Wonderland'; // This will affect obj1 as well
console.log(obj1.address.city); // Outputs: New Wonderland
// To create a deep copy
let obj3 = JSON.parse(JSON.stringify(obj1));
obj3.address.city = 'New Wonderland'; // This will not affect obj1
console.log(obj1.address.city); // Outputs: Wonderland
In summary, reference values in JavaScript are stored in heap memory, and variables hold references to these memory locations. Understanding how to manipulate these references correctly is essential for writing efficient and bug-free code. By following best practices and being aware of common pitfalls, you can effectively manage reference values in your applications.