[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.

JS
let name = "Jon"
console.log(name) // Jon
let name2 = name
console.log(name2) // Jon
name = "Sam"
console.log(name2) // Jon

What happens behind the scene:

1 2 3

Reference Example

Variables containing objects does not contain object, but reference to it (points to it)

JS
const obj = { x: 1 }
const obj2 = obj
obj.x = 10
console.log(obj.x) // 10
console.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.

4 5 6

More Example

JS
const i = 10
const 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 i
console.log(i)
// someStr changes b/c the object doesn't get passed, but a reference pointer
console.log(obj.someStr)

Copying values of reference data type

JS
// Copying elements of objects
const obj = { name: "A", age: 10 }
const obj2 = Object.assign({}, obj) // ES5
const obj3 = { ...obj } // ES6
// Copying elements of array
const arr = [1, 2, 3];
const arr2 = arr.slice(); // ES5
const 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.

JS
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.


WRITTEN BY

Keeping a record