JavaScript uses two main memory spaces to store variables:
- Memory Heap → where objects, arrays, functions live
- Call Stack → where execution happens; stores variable references (pointers)
What is the Stack?
Stack is a data structure that obeys the Last In First Out (LIFO) principle. This implies that the last item to enter the stack goes out first.
Imagine a pile of books stacked up on a shelf. The last book ends up being the first to be removed. Data stored inside the stack can still be accessed easily.
What is the Heap?
Reference data are stored inside the heap. When reference data is created, the variable of the data is placed on the stack, but the actual value is placed on the heap.
In JavaScript, different data types have different behaviors and locations in memory. So to reduce the chances of having bugs in your code, you need to understand the concept of mutability and immutability in JavaScript.
But the real difference between var, let, and const is how they are handled inside the Call Stack during creation and access, especially during hoisting.
var, let, and const control whether you can reassign the variable. Mutability controls whether the value itself can be changed. These are two different things.
Mutability
Mutability refers to data types that can be accessed and changed after they've been created and stored in memory. If a data type is mutable, that means that you can change it. Mutability allows you to modify existing values without creating new ones.
const staff = {
name: "Strengthened",
age: 43,
hobbies: ["reading", "Swimming"]
}
const staff2 = staff;
staff2.age = 53;
console.log(staff.age); // 53
console.log(staff2.age); // 53
Reference data does not copy values, but rather pointers.
Changing the age of staff2 updates the age of the staff object. Now you know it is because both point to the same object.
Immutability
Immutability refers to data types that you can't change after creating them, but that you can still access in memory. A value is immutable when altering it is impossible. Primitive data types are immutable, as we discussed above.
let student1 = "Halina";
let student2 = student1;
student1 = "Brookes"
console.log(student1); // Brookes
console.log(student2); // Halina
Source: https://www.freecodecamp.org/news/mutability-vs-immutability-in-javascript/


Top comments (0)