0
0
Typescriptprogramming~15 mins

Fresh object literals vs variable assignment behavior in Typescript - Hands-On Comparison

Choose your learning style9 modes available
Fresh object literals vs variable assignment behavior
📖 Scenario: Imagine you are managing a simple inventory system where you track items and their quantities. You want to understand how creating new objects directly differs from assigning existing objects to new variables.
🎯 Goal: You will create an object representing an item, then assign it to another variable. You will also create a fresh object literal with the same properties. Finally, you will compare how changing one affects the other.
📋 What You'll Learn
Create an object literal called item1 with properties name set to 'apple' and quantity set to 10.
Create a variable called item2 and assign it the value of item1.
Create a fresh object literal called item3 with the same properties as item1.
Change the quantity of item2 to 20.
Print the quantity of item1 and item3 to observe the difference.
💡 Why This Matters
🌍 Real World
Understanding object references is important when managing data in apps, like updating user profiles or inventory items without accidentally changing other data.
💼 Career
Many programming jobs require careful handling of objects and data structures to avoid bugs caused by unintended shared references.
Progress0 / 4 steps
1
Create the initial object literal
Create an object literal called item1 with properties name set to 'apple' and quantity set to 10.
Typescript
Need a hint?

Use curly braces {} to create an object with the given properties.

2
Assign the object to a new variable
Create a variable called item2 and assign it the value of item1.
Typescript
Need a hint?

Use = to assign item1 to item2.

3
Create a fresh object literal with the same properties
Create a fresh object literal called item3 with the same properties as item1: name set to 'apple' and quantity set to 10.
Typescript
Need a hint?

Create a new object literal just like item1, but assign it to item3.

4
Change quantity and print results
Change the quantity of item2 to 20. Then print the quantity of item1 and item3 using console.log.
Typescript
Need a hint?

Remember that item2 and item1 point to the same object, so changing one changes the other. item3 is a fresh object and stays unchanged.