DEV Community

Vasil Vasilev
Vasil Vasilev

Posted on

Mutable And Immutable Values in Javascript

Image description

In JavaScript there are two types of data types - primitive types and objects. Whenever you define a variable, the JavaScript engine allocates a memory to it. It stores all variable names on the Stack, while the values are either on the Stack or on the Heap.

let str = "hello"; 
// str (variable name) is stored on the Stack
// 'hello' (value) is stored on the Stack

let obj = { fname: "Vasil", lname: "Vasilev"} 
// obj (variable name) is stored on the Stack
// {...} the value is stored on the Heap
Enter fullscreen mode Exit fullscreen mode

NB: The { fname: "Vasil", lname: "Vasilev"} is merely a reference which points to the actual value stored on the Heap.

Any data type value which is immutable is stored on a Stack data structure since it’s size is known during compilation phase.

Mutable data types such as Objects, Arrays are stored on a Heap data structure and a reference to the Object or array is stored on the stack data structure.

Top comments (0)