JavaScript Data Structures Tutorial – Learn its Types and Implementation

Next article in JavaScript DataFlair Tutorial Series will focus on different data structures in JavaScript. We will start with understanding what data structures are, then we will continue with its classification. Also, we will understand some of the basic data structures in a little more depth. But before we start with our tutorial on JavaScript Data Structure, we would recommend you to go through our previous tutorial on JavaScript Array. This is because you need to have a basic understanding of JavaScript to be able to understand this topic.

What are JavaScript Data Structures?

A JavaScript Data Structure is a specific technique to organize and store data in a computer so that we can access and modify it efficiently. More accurately, it is a collection of data values, the relationships among them, and the functions or operations that we can apply to the data.

Some of the advantages of using data structures are as follows:

  • They provide an easy way to manage large datasets.
  • They simplify the processing of data on a computer.
  • These are essential for designing efficient program algorithms.

But, only advanced users can make changes to data structures. So if you run into any problem, you’ll need an expert’s advice. The diagram below illustrates the types of data structures available in every programming language, including JavaScript. You will see some other data structures including trie, but these are advanced topics and it’s not relevant to mention them here.

JavaScript-data-structures

Types of Data Structures in JavaScript

We discussed various primitive data structures that JavaScript provides in our prior tutorial on Data Types in JavaScript. This tutorial will focus on non-primitive data structures. They are as follows:

  • A linear data structure traverses its elements sequentially. We can reach only one data item directly. To access other elements, you need the help of that base element.
  • Unlike linear data structures, non-linear data structures don’t traverse in a sequence. Every data item connects with numerous other items, reflecting specific relationships.
  • Static data structures have a fixed memory size, that is, you need to state the maximum size of the structure well in advance. We cannot allocate the memory later. The example of static data structure is arrays. We learned about them in the DataFlair’s previous tutorial on JavaScript Arrays.
  • Dynamic data structures differ from static data structures in the way that we can modify the memory size allocated to it. These include queue, stack and linked lists.

The following table states the difference between static and dynamic data structures very clearly.

Static Data Structures
Dynamic Data Structures
Memory is either wasted (underflow) or is insufficient (overflow).
The amount of memory allocated varies, preventing memory wastage.
Fast access to the data elements since the memory location is decided while writing the program.
Slower access to each element since memory allocation happens at run time.
Structures have fixed size, making them predictable and easier to work with.
Structures vary in size, thus complex algorithms are necessary to deal with them.
The relationship between different elements remains constant.
The relationship between the elements changes as the program executes.

1. Linked List

A linked list maintains a list in the memory. The script has the base address of the first element, that contains the link to the next element in the list. You can only access an element (except the base element) using the previous element.

Linked List - JavaScript Data Structures

Linked lists store these elements in what we call a node. A node comprises of a data value and the link (address) to the next element. The first node is the head while the last node is the tail of the list. The tail, as shown in the diagram, contains the value NULL in place of a link. The code below creates a node:

Code:

<html>
  <body>

    <script>
      class Node { //defining a JavaScript class
          constructor(data) { //constructor method
              this.data = data; //data value of the node
              this.next = null; //link of the next node
          }
      }
      const head = new Node(12); //creating a node
    </script>

  </body>
</html>

Screenshot:

node.datastructure

Output:

node.datastructure op

Let’s add another node in our code with the following statement at the end of the script:

head.next = new Node(45);

The output in your console window will look something like this:

node.datastructure op2

Note that now the next of the first element contains the link of the subsequent element.

There is a more efficient way to add several nodes to a linked list effectively, but they are not part of basic JavaScript. As you grow as a programmer, you will gain a better understanding of how it works.

2. Stack

stack - JavaScript Conditional Statements

A stack is an ordered list which follows LIFO (last in first out) algorithm. You can access the elements of a stack from only a single end, called top. A very common example of a stack, we see in our daily lives, is the stack of chairs. You can only access the top chair at a time. The only way to reach a chair in the middle is by going through all the chairs above it. In our very first tutorial on Introduction to JavaScript, we learned about the call stack which works with the instructions we want to execute. Stacks are crucial for programming, so you must know them well because you are going to work with them a lot while developing.

We can implement a stack using a static data structure (array) or a linked list. Both approaches have their own advantages but as a beginner, we will implement stack using an array. The code below creates a new stack and pushes two elements in the stack using the predefined push() function:

Code:

<html>
  <body>

    <script>
      let stack = []; //create empty stack using array
      //push
      stack.push(65);
      stack.push(10);
    </script>

  </body>
</html>

Screenshot:
stack

I removed the top element from my stack directly from the console using the pop() function. You can add the statement in your source code as well. The output will look something like this:

stack op

3. Queue

queue - JavaScript Data Structures

A queue is another type of ordered list which follows FIFO (first in first out) algorithm. It has two ends, front (elements added) and rear (elements removed). A common example you may see is a queue of cars in a one-way lane. The first car that enters the lane is the first one to exit. Also, the car in the middle cannot exit the queue until all the cars before it.

The process of inserting an element in the queue is enqueueing while removing an element is dequeuing. Similar to stacks, we can implement queues with the help of both an array and a linked list. Both approaches have their pros and cons, as explained in the difference between static and dynamic data structures. The array implementation of a queue is clear in the example below. Note that I performed dequeue directly on the Browser Console Window.

Code:

<html>
  <body>

    <script>
      let queue = []; //create an empty queue
      //enqueue
      queue.push(65);
      queue.push(10);
    </script>

  </body>
</html>

Screenshot:

queue

Output:

queue op

4. Tree

root node - JavaScript data structures

A JavaScript tree is a special data structure that implements the hierarchical tree structure with a root node, child and parent nodes and leaf nodes represented as a set of linked nodes. A tree data structure is a collection of nodes, starting with a root node, with data values in each of the nodes along with the reference to the child nodes. The root node has no parent node and the leaf nodes have no child nodes. If the child node of a parent node has one or more child nodes, it is a subtree. In the diagram above, the nodes BEF (T1) and DGH (T2) form two subtrees.

5. Graph

A graph is a group of a finite number of vertices and edges that connect these vertices. The edges can be ‘directed’ (directed graph) and ‘undirected’ (undirected graph). Unlike trees, who maintain a parent-child relationship between their nodes (vertices), the nodes of the graph maintain a complex relationship among them.

directed undirected graph - JavaScript Data Structures

6. Hash table

hash table - JavaScript Data Structures

A hash table, or hash map, is a data structure that implements associative arrays since it maps keys to values. It uses a hash function to determine the index of the data value in the array (bucket). These buckets help to identify the storage location of the data we want. The earlier version of JavaScript didn’t support associative arrays, so there was no built-in hash table available. But as the developers introduced new features, JavaScript gained additional functionality and addition of associative arrays was one of them.

Summary

Here we conclude our tutorial on JavaScript Data Structures. In this article, we learned about some of the data structures of JavaScript. There are many more you will learn about as you practice JavaScript, but for now, these are the ones you need to focus on. Be very attentive when you learn or practice about these structures since these are common for all programming languages. Once you clear your concepts, all that is left is the syntax of the program, and that is quite easy.

The next tutorial for you – JavaScript Characters

Hope the information provided was fruitful for you.

Feel free to drop your queries and feedback in the comment section below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.