0
0
Typescriptprogramming~5 mins

Fresh object literals vs variable assignment behavior in Typescript

Choose your learning style9 modes available
Introduction
Understanding how new objects and variable assignments work helps you avoid bugs when changing data.
When you want to create a new object without affecting others.
When you assign one variable to another and want to know if they share the same object.
When you want to change an object but keep the original safe.
When you want to compare if two variables point to the same object.
Syntax
Typescript
const obj1 = { key: 'value' };
const obj2 = obj1; // obj2 points to the same object
const obj3 = { key: 'value' }; // fresh new object
Assigning one object variable to another copies the reference, not the object itself.
Creating a fresh object literal makes a new object in memory.
Examples
Both a and b point to the same object, so changing b changes a too.
Typescript
const a = { name: 'Alice' };
const b = a;
b.name = 'Bob';
console.log(a.name);
a and b are different objects, so changing b does not affect a.
Typescript
const a = { name: 'Alice' };
const b = { name: 'Alice' };
b.name = 'Bob';
console.log(a.name);
a and b are the same object (true), a and c are different objects (false).
Typescript
const a = { count: 1 };
const b = a;
const c = { count: 1 };
console.log(a === b);
console.log(a === c);
Sample Program
Changing copy changes original because they point to the same object. Fresh is a new object, so it stays unchanged.
Typescript
const original = { score: 10 };
const copy = original;
const fresh = { score: 10 };

copy.score = 20;

console.log('original.score:', original.score);
console.log('fresh.score:', fresh.score);

console.log('original === copy:', original === copy);
console.log('original === fresh:', original === fresh);
OutputSuccess
Important Notes
Objects are stored by reference, so assigning copies the reference, not the object.
Fresh object literals create new objects in memory, even if they look the same.
Use fresh objects when you want to avoid unexpected changes to shared data.
Summary
Assigning an object variable copies the reference, not the object itself.
Fresh object literals create new, separate objects.
Changing one reference affects all variables pointing to the same object.