When working with languages like JavaScript, Java, C#, Python, and many others, you will always encounter two fundamental concepts: Value Types and Reference Types. They may sound a bit technical, but they simply describe how data is stored in memory and how it behaves when assigned to variables or passed to functions.
-
- What Value Types are
- What Reference Types are
- Why the difference matters
- Common bugs caused by misunderstanding the two
- Practical examples (JavaScript and C#)
1. What Is a Value Type?
- Number (int, float…)
- Boolean
- Char
- Struct (C#)
- Enum
let a = 10;
let b = a; // b receives a copy
a = 20;
console.log(a); // 20
console.log(b); // 10
2. What Is a Reference Type?
- Object
- Array
- Function
- Class instances
- Collections (List, Dictionary, Map…)
let obj1 = { name: "David" };
let obj2 = obj1; // both point to the same object
obj1.name = "Alex";
console.log(obj1.name); // Alex
console.log(obj2.name); // Alex
3. Value Types vs Reference Types: Visual Summary
| Feature | Value Type | Reference Type |
|---|---|---|
| Stored in | Stack | Heap (reference on stack) |
| What is stored | Actual value | Address pointing to data |
| Assignment behavior | Copies the value | Copies the reference |
| Independence between variables | Yes | No |
| Examples | int, float, bool | object, array, class |
4. Shallow Copy vs Deep Copy
Shallow Copy
Copies only the top-level structure; nested objects still share references.Deep Copy
Copies all levels of data; nothing is shared.
let obj1 = { name: "Dũng", info: { age: 30 }};
let obj2 = structuredClone(obj1);
obj1.info.age = 31;
console.log(obj2.info.age); // 30 (independent)
5. Final Thoughts
Key takeaway- Value Types store actual values
- Reference Types store memory references
- Copying a Value Type creates an independent variable
- Copying a Reference Type creates shared memory
- Copying a Reference Type creates shared memory