0
0
Typescriptprogramming~3 mins

Fresh object literals vs variable assignment behavior in Typescript - When to Use Which

Choose your learning style9 modes available
The Big Idea

What if changing one object secretly changes another? Discover how fresh object literals save you from this hidden trap!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
const obj1 = { name: 'Alice' };
const obj2 = obj1;
obj2.name = 'Bob';
console.log(obj1.name); // Outputs 'Bob'
After
const obj1 = { name: 'Alice' };
const obj2 = { ...obj1 };
obj2.name = 'Bob';
console.log(obj1.name); // Outputs 'Alice'
What It Enables

It lets you create independent objects effortlessly, avoiding unexpected bugs and making your code more reliable.

Real Life Example

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.

Key Takeaways

Assigning variables copies references, not objects.

Fresh object literals create new, independent objects.

This prevents bugs from shared object changes.