What if changing one object secretly changes another? Discover how fresh object literals save you from this hidden trap!
Fresh object literals vs variable assignment behavior in Typescript - When to Use Which
Imagine you want to create multiple objects that look similar but have their own separate values. You try to copy one object by just assigning it to a new variable, thinking they will be independent.
But when you change one object, the other changes too! This happens because the variables point to the same object in memory. Manually tracking and copying each property is slow and easy to mess up.
Using fresh object literals means creating a brand new object each time. This way, each variable holds its own separate object, so changes don't affect others. It's clean, safe, and easy to understand.
const obj1 = { name: 'Alice' };
const obj2 = obj1;
obj2.name = 'Bob';
console.log(obj1.name); // Outputs 'Bob'const obj1 = { name: 'Alice' };
const obj2 = { ...obj1 };
obj2.name = 'Bob';
console.log(obj1.name); // Outputs 'Alice'It lets you create independent objects effortlessly, avoiding unexpected bugs and making your code more reliable.
Think of making two separate user profiles in an app. You want to change one profile's name without accidentally changing the other. Fresh object literals make this safe and simple.
Assigning variables copies references, not objects.
Fresh object literals create new, independent objects.
This prevents bugs from shared object changes.