Value Types vs Reference Types
- Primitives or value types are copied by their value
- Reference types or objects, are copied by their reference.
Values Types
- In value types, the value is stored inside of this variable.
- When you copy, value that is stored in the variable is copied into this new variable. Example 1
let x = 10;
let y = x;
x = 20;
Example 2
let x = 10;
function change(param) {
param = 30;
}
change(x);
Reference Types
- In reference types, the object is stored somewhere in the memory, and the address of that memory location is stored inside the variable
- When you copy, the address or the reference that is copied
Example 1
let x = {value: 10};
let y = x;
x.value = 20;
Example 2
let x = {value: 10};
function change(param) {
param.value = 30;
}
change(x);