If we implement a DataStructure in JavaScript, will the browsers underlying implementation use same data structure for handling data?
A Linked List for example – we will have a Node structure something like this
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
Now let’s say we set next to another node to create a linked list.
Does next really point to next Node using Linked List in underlying implementation? Linked List has O(1) to add a new node. Will this be actually same O(1) for JavaScript too when C++ (or any JavaScript engine) converts the implementation to system level ?
>Solution :
In JavaScript, identifiers (variables and arguments) and properties of objects are all essentially pointers to structures in memory (or on the heap).
Say that you have two Nodes like in your code, one linked to the other. One way to visualize the resulting structure is:
<Node>: memory address 16325
data: memory address 45642 (points to whatever argument was passed)
next: memory address 62563
<Node>: memory address 62563 (this is the same as the `next` above)
data: memory address 36425 (points to whatever argument was passed)
next: memory address 1 (points to null)
That’s not exactly what happens, but it’s close enough for the "underlying implementation" you’re concerned about. If, in your JavaScript, you have a reference to one Node, and you link it to another by assigning to its next property, what’s involved under the hood is simply taking the location of the linked object and changing the original object’s next property to point to that location. And yes, that operation takes next to no processing power – it’s definitely an O(1) process in any reasonable implementation, such as in browsers and Node.
The JavaScript engine does not have to re-analyze the structure from the ground up when a new property is created somewhere – it’s all just objects and properties linking to other objects.