[JS]: Primitive vs Reference
JS
09/27/2019
Different data types in JavaScript
Primitive Values (Stored in Stack)
- String
- Number
- Boolean
- Undefined
- Null
- Symbol (ES6)
Reference Values (Stored in Heap)
- Array
- Object
- Function
- ...
Data in stack can be access relative quicker than data in heap
But, heap is able to hold more information compared to stack
Primitive Example
Variables containing primitives hold data inside of variable itself.
For example below, by assigning name2 = name
, the value of "Jon" gets copied.
let name = "Jon"console.log(name) // Jon
let name2 = nameconsole.log(name2) // Jon
name = "Sam"
console.log(name2) // Jon
What happens behind the scene:
Reference Example
Variables containing objects does not contain object, but reference to it (points to it)
const obj = { x: 1 }const obj2 = objobj.x = 10
console.log(obj.x) // 10console.log(obj2.x) // 10
const obj = { x:1 }
creates a new object in the heap, but we have a pointer in stack which stores teh reference(address) to the created element. So the obj contains the pointer, not the actual copy unlike primitive types.
const obj2
that points to obj
has its own pointer, but it will point to the same object that was previously created in the heap.
More Example
const i = 10const obj = { someStr: "A" }
const update = (a, b) => { a = 20 b.someStr = "B"}
update(i, obj)
// i doesn't change; when arg is passed, it creates a simple copy, so it won't change the value of iconsole.log(i)
// someStr changes b/c the object doesn't get passed, but a reference pointerconsole.log(obj.someStr)
Copying values of reference data type
// Copying elements of objectsconst obj = { name: "A", age: 10 }const obj2 = Object.assign({}, obj) // ES5const obj3 = { ...obj } // ES6
// Copying elements of arrayconst arr = [1, 2, 3];const arr2 = arr.slice(); // ES5const arr3 = [...arr]; // ES6
Potential issue (Deep Cloning)
Although person2
copied values from person
, changing the value of personality[0]
affects the person2
because the values were not deeply copied or deeply cloned. i.e. shallow cloned.
const person = { name: "Ellis", personality: ["cool", "nice"],};
const person2 = { ...person };person.personality[0] = "not cool";
console.log(person2);
To execute deep cloning or array/object, use of library like LoDash is preferred.