DEV Community

Cover image for Javascript Data Types in Depth(2)
waqas
waqas

Posted on

Javascript Data Types in Depth(2)

In JavaScript, there are only two main non-primitive data types: objects and arrays. These data types are considered non-primitive because they are complex data structures that can be used to store and organize many different types of data.

1.Arrays
2.objects

Lets Learn prerequisites first

Heap

In computer science, the heap is a region of memory that is used to store objects and other complex data structures. It is a dynamic data structure, which means that it can grow and shrink in size as needed to accommodate the data being stored in it.

Stack
In computer science, the stack is a region of memory that is used to store primitive data types and the memory addresses of data structures on the heap. It is a Last In First Out (LIFO) data structure, which means that the last item added to the stack is the first item that can be removed.

So How Non Primitive(reference) Data Type Work

When you create a new object or array in JavaScript, the data structure is stored on the heap and a reference to it is stored on the stack. This means that when you access the object or array, you are actually accessing the reference on the stack, which points to the data on the heap.

`let arr =[1,2,3,4,5]

// The "arr" array is stored on the heap
// A reference to the "arr" array is stored on the stack

let person = {
name: "John Doe",
age: 35
};

// The "person" object is stored on the heap
// A reference to the "person" object is stored on the stack
`

But What Happen When We Mutate Array or Object

When you mutate an array or object in JavaScript, the data on the heap is updated to reflect the changes, but the reference on the stack remains the same. This means that when you access the array or object after mutating it, you are still using the same reference on the stack to find the updated data on the heap.
`
// Create a new array
let numbers = [1, 2, 3];

// The "numbers" array is stored on the heap
// A reference to the "numbers" array is stored on the stack

// Mutate the array
numbers.push(4);

// The data on the heap is updated to [1, 2, 3, 4]
// The reference on the stack remains the same

// Access the array
let lastNumber = numbers[3];

// The reference on the stack is used to find the updated data on the heap`

codepen link
"https://codepen.io/waqas-on-github/pen/vYrwNaz?editors=0012"

Top comments (0)