{"id":9379,"date":"2021-06-04T09:00:25","date_gmt":"2021-06-04T13:00:25","guid":{"rendered":"https:\/\/blog.logrocket.com\/?p=9379"},"modified":"2024-06-04T17:20:03","modified_gmt":"2024-06-04T21:20:03","slug":"know-your-javascript-data-structures","status":"publish","type":"post","link":"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/","title":{"rendered":"Know your JavaScript data structures"},"content":{"rendered":"<!DOCTYPE html>\n<html><p><em><strong>Editor\u2019s note: <\/strong>This article was updated in June 2021 to reflect reader-reported corrections and suggestions as well as updates to the code.<\/em><\/p><img loading=\"lazy\" decoding=\"async\" width=\"730\" height=\"487\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/know-your-javascript-data-structures-nocdn.jpg\" class=\"attachment-full size-full wp-post-image\" alt=\"Know Your JavaScript Data Structures\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/know-your-javascript-data-structures-nocdn.jpg 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/know-your-javascript-data-structures-nocdn-300x200.jpg 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\">\n<h2>What are JavaScript data structures?<\/h2>\n<p>JavaScript data structures are often overlooked \u2014 or, rather, we don\u2019t think about them much. The problem with ignoring data structures is that for many companies, you are usually required to have a deep understanding of how to manage your data. A strong grasp of data structures will also help you in your day-to-day job as you approach problems.<\/p>\n<p>In this article, the data structures we will be discussing and implementing are:<\/p>\n<ul>\n<li>Stack<\/li>\n<li>Queue<\/li>\n<li>Linked list<\/li>\n<li>Hash table<\/li>\n<li>Trees<\/li>\n<\/ul>\n<h2 id=\"stack\">Stack<\/h2>\n<p>The first JavaScript data structure we are discussing is the stack. This is quite similar to the queue, and you may have heard of the <code>call stack<\/code> before, which is what JavaScript uses to handle events.<\/p>\n<p>Visually, the stack looks like this:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-54942\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/stack-data-structure-visual-1.png\" alt=\"stack data structure visual\" width=\"730\" height=\"544\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/stack-data-structure-visual-1.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/stack-data-structure-visual-1-300x224.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\" \/><\/p>\n<p>So when you have a stack, the last item you pushed on the stack will be the first one removed. This is referred to as last-in, first-out (LIFO). The back button in web browsers is a good example: each page you view is added to the stack, and when you click back, the current page (the last one added) is popped from the stack.<\/p>\n<p>That is enough theory. Let\u2019s get into some code. For the stack, we are going to use an object and pretend that JavaScript doesn\u2019t have an array data structure. Then when we move onto the queue data structure, we will use an array.<\/p>\n<pre>class Stack {\n  constructor() {\n<em>    \/\/ create our stack, which is an empty object<\/em>\n    this.stack = {}\n  }\n<em>  \/\/ this method will push a value onto the top of our stack<\/em>\n  push(value) {\n\n  }\n<em>  \/\/ this method is responsible for popping off the last value and returning it<\/em>\n  pop() {\n\n  }\n\n<em>  \/\/ this will peek at the last value added to the stack<\/em>\n  peek() {\n\n  }\n}<\/pre>\n<p>I\u2019ve added comments to the above code, so hopefully, you are with me up to this point. The first method we will implement is the <code>push<\/code> method.<\/p>\n<p>Let\u2019s think about what we need this method to do:<\/p>\n<ul>\n<li>We need to accept a value<\/li>\n<li>We then need to add that value to the top of our stack<\/li>\n<li>We also should track the length of our stack so we know our stack\u2019s index<\/li>\n<\/ul>\n<p>It would be great if you could try this yourself first, but if not, the complete <code>push<\/code> method implementation is below:<\/p>\n<pre>class Stack {\n  constructor() {\n    this._storage = {};\n    this._length = 0; <em>\/\/ this is our length<\/em> \n  }\n\n  push(value) {\n    <em>\/\/ so add the value to the top of our stack<\/em>\n    this._storage[this._length] = value;\n    <em>\/\/ since we added a value, we should also increase the length by 1<\/em>\n    this._length++;\n  }\n  \/\/\/ .....\n}<\/pre>\n<p>I bet it was easier than you thought \u2014 with lot of these structures, they sound more complicated than they actually are.<\/p>\n<p>Now let\u2019s get to the <code>pop<\/code> method. The goal with the <code>pop<\/code> method is to remove the last value that was added to our stack and then return that value. Try this yourself first if you can, otherwise just continue on to see the solution:<\/p>\n<pre>class Stack {\n  constructor() {\n    this._storage = {};\n    this._length = 0;\n  }\n  \n  pop() {\n    const lastValIndex = this._length - 1;\n    if (lastValIndex &gt;= 0) {\n      <em>\/\/ we first get the last val so we have it to return<\/em>\n      const lastVal = this._storage[lastValIndex];\n      <em>\/\/ now remove the item which is the length - 1<\/em>\n      delete this._storage[lastValIndex];\n      <em>\/\/ decrement the length<\/em>\n      this._length--;\n      <em>\/\/ now return the last value<\/em>\n      return lastVal;\n    }\n    return false;\n  }\n}<\/pre>\n<p>Cool! Nearly there. The last thing we need to do is the <code>peek<\/code> function, which looks at the last item in the stack. This is the easiest function: we simply return the last value. Implementation is:<\/p>\n<pre>class Stack {\n  constructor() {\n    this._storage = {};\n    this._length = 0;\n  }\n  \n  peek() {\n    const lastValIndex = this._length - 1;\n    const lastVal = this._storage[lastValIndex];\n    return lastVal;\n  }\n}<\/pre>\n<p>This is pretty similar to the <code>pop<\/code> method, but this time, we do not remove the last item.<\/p>\n<p>Yes! That is our first data structure covered. Now let\u2019s move on to the queue, which is quite similar to the stack.<\/p>\n<h2 id=\"queue\">Queue<\/h2>\n<p>The queue is the next structure we will discuss \u2014 hopefully the stack is still fresh in your brain because the queue is quite similar. The key difference between the stack and the queue is that the queue is first-in, first-out (FIFO). <span class=\" author-d-1gg9uz65z1iz85zgdz68zmqkz84zo2qoxw4k3z71zz84zz67zpfz74z2vmz71zvz73z9xz72zz68z3irz122zqz68zhmo8j\">There have been a few comments on this article asking why not use an array here, so as a contrast to the above, we will use an array for this data structure.<\/span><\/p>\n<p>Visually, we can represent it like this:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-9423\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/queue-data-structure-visual.png\" alt=\"Visual Representation Of A Queue\" width=\"730\" height=\"516\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/queue-data-structure-visual.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/queue-data-structure-visual-300x212.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\" \/><\/p>\n<p>The two big actions are <code>enqueue<\/code> and <code>dequeue<\/code>. We add to the back and remove from the front. <span class=\" author-d-1gg9uz65z1iz85zgdz68zmqkz84zo2qoxw4k3z71zz84zz67zpfz74z2vmz71zvz73z9xz72zz68z3irz122zqz68zhmo8j\">Let\u2019s get into implementing a queue to get a better understanding. I had previously used an object here, but I have updated it now to use an array. For the stack data structure, you can also do this approach.<\/span><\/p>\n<p>The core structure of our code will look like this:<\/p>\n<pre>class Queue {\n  constructor() {\n    \/\/ array to hold our values\n    this.queue = [];\n    \/\/ length of the array - could also track this with queue.length\n    this.length = 0;\n  }\n\n  enqueue(value) {\n   \n  }\n\n  dequeue() {\n    \n  }\n  \n  peek() {\n    \n  }\n}<\/pre>\n<p>Let\u2019s first implement our <code>enqueue<\/code> method. Its purpose is to add an item to the back of our queue.<\/p>\n<pre>enqueue(value) {\n<em>  \/\/ add a value to the back of the queue<\/em>\n  this.queue.push(value);\n<em>  \/\/ update our length (can also be tracked with queue.length)<\/em>\n  this.length++;\n}<\/pre>\n<p>This is quite a simple method that adds a value to the end of our queue, but you may be a little confused by <code>this.queue[this.length + this.head] = value;<\/code>.<\/p>\n<p>Let\u2019s say our queue looked like this: <code>{14 : 'randomVal'}<\/code>. When adding to this, we want our next key to be <code>15<\/code>, so it would be length(1) + head(14), which gives us <code>15<\/code>.<\/p>\n<p>The next method to implement is the <code>dequeue<\/code> method (remove an item from the front of our queue):<\/p>\n<pre>dequeue() {\n<em>  \/\/ if we have any values<\/em>\n  if (this.length &gt; 0) {\n<em>    \/\/ remove an element from the front of the queue<\/em>\n    this.queue.shift();\n<em>    \/\/ decrement the length<\/em>\n    this.length--;\n  }\n}<\/pre>\n<p>The final method to implement is the <code>peek<\/code> method, which is an easy one (return the first value of the queue):<\/p>\n<pre>peek() {\n  if(this.length &gt; 0) {\n    return this.queue[0];  \n  }\n  return null;\n  }<\/pre>\n<p>That\u2019s it for the queue \u2014 let\u2019s move on to the linked list data structure.<\/p>\n<h2>Linked list<\/h2>\n<p>Let\u2019s discuss the formidable linked list. This is more complicated than our structures above, but together, we can figure it out.<\/p>\n<p>The first question you might ask is why we would use a linked list. A linked list is mostly used for languages that do not have dynamic sizing arrays. Linked lists organize items sequentially, with each item pointing to the next item.<\/p>\n<p>Each node in a linked list has a <code>data<\/code> value and a <code>next<\/code> value. Below, <code>5<\/code> is the data value, and the <code>next<\/code> value points to the next node, i.e., the node that has the value <code>10<\/code>.<\/p>\n<p>Visually, the linked list data structure looks like this:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-54944\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/linked-list-data-structure-visual-1.png\" alt=\"linked list javascript data structure visual\" width=\"730\" height=\"223\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/linked-list-data-structure-visual-1.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/linked-list-data-structure-visual-1-300x92.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\" \/><\/p>\n<blockquote><p>As a side note, a previous pointer is called a doubly linked list.<\/p><\/blockquote>\n<p>In an object, the above <code>LinkedList<\/code> would look like the following:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-54946\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/linkedlist-in-object-1.png\" alt=\"linkedlist javascript structure object\" width=\"531\" height=\"332\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/linkedlist-in-object-1.png 531w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/linkedlist-in-object-1-300x188.png 300w\" sizes=\"auto, (max-width: 531px) 100vw, 531px\" \/><\/p>\n<p>You can see that the last value <code>1<\/code> has a <code>next<\/code> value of <code>null<\/code>, as this is the end of our <code>LinkedList<\/code>.<\/p>\n<p>So now, how would we implement this?<\/p>\n<p>The first thing we are going to create is a <code>Node<\/code> class.<\/p>\n<pre>class Node {\n  constructor(data, next = null) {\n    this.data = data;\n    this.next = next;\n  }\n}<\/pre>\n<p>The above represents each node in our list.<\/p>\n<p>With a class for our <code>Node<\/code>, the next class we need is our <code>LinkedList<\/code>.<\/p>\n<pre>class LinkedList {\n  constructor() {\n    this.head = null;\n    this.size 0;\n  }\n}<\/pre>\n<p>As explained above, our <code>LinkedList<\/code> has a <code>head<\/code>, which is first set to <code>null<\/code> (you could add an <code>arg<\/code> to your constructor to set this if you wanted). We also track the <code>size<\/code> of our linked list.<\/p>\n<p>The first method we are going to implement is <code>insert<\/code>; this will add a <code>node<\/code> to our linked list<\/p>\n<pre><em>\/\/ insert will add to the end of our linked list<\/em>\ninsert(data) {\n  \/\/ create a node object using the data passed in\n  let node = new Node(data);\n  let current;\n<em>  \/\/ if we don't have a head, we make one<\/em>\n  if (!this.head) {\n    this.head = node;\n  } else {\n<em>    \/\/ if there is already a head, then we add a node to our list<\/em>\n    current = this.head;\n<em>    \/\/ loop until the end of our linked list (the node with no next value)<\/em>\n    while (current.next) {\n      current = current.next;\n    }\n<em>    \/\/ set the next value to be the current node<\/em>\n    current.next = node;\n  }\n<em>  \/\/ increment the size<\/em>\n  this.size++;\n}<\/pre>\n<p>I have commented in the code above to make it easier to understand, but all we are doing is adding a <code>node<\/code> to the end of the linked list. We can find the end of our linked list by finding the <code>node<\/code> that has a <code>next<\/code> value of <code>null<\/code>.<\/p>\n<p>The next method we are going to implement is <code>removeAt<\/code>. This method will remove a <code>node<\/code> at an index.<\/p>\n<pre><em>\/\/ Remove at index<\/em>\n  removeAt(index) {\n<em>    \/\/ check if index is a positive number and index isn't too large<\/em>\n    if (index &lt; 0 || index &gt; this.size) {\n      return;\n    }\n    \/\/ start at our head\n    let current = this.head;\n<em>    \/\/ keep a reference to the previous node<\/em>\n    let previous;\n<em>    \/\/ count variable<\/em>\n    let count = 0;\n<em>    \/\/ if index is 0, then point the head to the item second (index 1) in the list<\/em>\n    if (index === 0) {\n      this.head = current.next;\n    } else {\n<em>      \/\/ loop over the list and<\/em> \n      while (count &lt; index) {\n<em>        \/\/ first increment the count<\/em>\n        count++;\n<em>        \/\/ set previous to our current node<\/em>\n        previous = current;\n <em>       \/\/ now set our current node to the next node<\/em>\n        current = current.next;\n      }\n<em>      \/\/ update the next pointer of our previous node to be the next node<\/em>\n      previous.next = current.next;\n    }\n<em>    \/\/ since we removed a node we decrement, the size by 1<\/em>\n    this.size--;\n  }<\/pre>\n<p>So the method above will remove a node at a specific index. It does this by updating the next value to point at the next node in the list until we reach the index. This means that no node will be pointing at the node at the index, so it will be removed from our list.<\/p>\n<p>The final (easiest) method left to do is <code>clearList<\/code>.<\/p>\n<pre>clearList() {\n  this.head = null;\n  this.size = 0;\n}<\/pre>\n<p>This just resets everything back to the start. There are lots of methods you can add to your linked list, but the above sets down the core fundamentals that you need to know.<\/p>\n<h2>Hash table<\/h2>\n<p>So the second-to-last data structure we are tackling is the mighty hash table. I purposefully placed this after the <code>LinkedList<\/code> explanation, as they are not a million miles away from each other.<\/p>\n<p>A hash table is a data structure that implements an associative array, which means it maps keys to values. A JavaScript object is a hash table, as it stores key-value pairs.<\/p>\n<p>Visually, this can be represented like so:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-9435\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/hash-table-data-structure-visual.png\" alt=\"Visual Representation Of A Hash Table\" width=\"730\" height=\"335\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/hash-table-data-structure-visual.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/hash-table-data-structure-visual-300x138.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\" \/><\/p>\n<p>Before we start talking about how to implement the hash table, we need to discuss the importance of the <em>hashing function.<\/em> The core concept of the hashing function is that it takes an input of any size and returns a hash code identifier of a fixed size.<\/p>\n<pre>hashThis('i want to hash this') =&gt; 7<\/pre>\n<p>The hashing function can be very complicated or straightforward. Each of your files on GitHub are hashed, which makes the lookup for each file quite fast. The core idea behind a hashing function is that given the same input will return the same output.<\/p>\n<p>With the hashing function covered, it\u2019s time to talk about how we would implement a hash table.<br>\nThe three operations we will discuss are <code>insert<\/code>, <code>get<\/code>, and, finally, <code>remove<\/code>.<\/p>\n<p>The core code to implement a hash table is as follows:<\/p>\n<pre>class HashTable {\n  constructor(size) {\n<em>    \/\/ define the size of our hash table, which will be used in our hashing function\n<\/em>    this.size = size;\n    this.storage = [];\n  }\n  insert(key, value) { }\n  get() {}\n  remove() {}\n<em>  \/\/ this is how we will hash our keys\n<\/em>  myHashingFunction(str, n) {\n    let sum = 0;\n    for (let i = 0; i &lt; str.length; i++) {\n      sum += str.charCodeAt(i) * 3;\n    }\n    return sum % n;\n  }\n}<\/pre>\n<p>Now let\u2019s tackle our first method, which is <code>insert<\/code>. The code to <code>insert<\/code> into a hash table is as follows (to keep things simple, this method will handle collisions but not duplicates):<\/p>\n<pre>insert(key, value) {\n<em>  \/\/ will give us an index in the array\n<\/em>  const index = this.myHashingFunction(key, this.size);\n<em>  \/\/ handle collision - hash function returns the same\n  \/\/ index for a different key - in complicated hash functions it is very unlikely\n  \/\/ that a collision would occur<\/em>\n  if (!this.storage[index]) {\n    this.storage[index] = [];\n  }\n<em>  \/\/ push our new key value pair<\/em>\n  this.storage[index].push([key, value]);\n}\n<\/pre>\n<p>So if we were to call the insert method like so:<\/p>\n<pre>const myHT = new HashTable(5);\nmyHT.insert(\"a\", 1);\nmyHT.insert(\"b\", 2);<\/pre>\n<p>What do you think our hash table would look like?<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-9437\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/hash-table-example-code.png\" alt=\"Hash Table Example Code\" width=\"730\" height=\"338\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/hash-table-example-code.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/hash-table-example-code-300x139.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\" \/><\/p>\n<p>You can see our key-value pair has been inserted into our table at index <code>1<\/code> and <code>4<\/code>.<\/p>\n<p>Now how would we remove a value from a hash table?<\/p>\n<pre>remove(key) {\n<em>    \/\/ first we get the index of our key\n    \/\/ remember, the hashing function will always return the same index for the same\n    \/\/ key<\/em>\n    const index = this.myHashingFunction(key, this.size);\n<em>    \/\/ remember we could have more than one array at an index (unlikely)<\/em>\n    let arrayAtIndex = this.storage[index];\n    if (arrayAtIndex) {\n<em>      \/\/ let's loop over all the arrays at that index<\/em>\n      for (let i = 0; i &lt; arrayAtIndex.length; i++) {\n<em>        \/\/ get the pair (a, 1)<\/em>\n        let pair = arrayAtIndex[i];\n<em>        \/\/ check if the key matches the key param<\/em>\n        if (pair[0] === key) {\n<em>          \/\/ delete the array at index<\/em>\n          delete arrayAtIndex[i];\n<em>          \/\/ job done, so break out of the loop<\/em>\n          break;\n        }\n      }\n    }\n}<\/pre>\n<p>Regarding the above, you may be thinking, \u201cIs this not linear time? I thought hash tables are meant to be constant?\u201d You would be correct in thinking that, but since this situation is quite rare with complicated hashing functions, we still consider hash tables to be constant.<\/p>\n<p>The final method we will implement is the <code>get<\/code> method. This is the same as the <code>remove<\/code> method, but this time, we return the <code>pair<\/code> rather than delete it.<\/p>\n<pre> get(key) {\n    const index = this.myHashingFunction(key, this.size);\n    let arrayAtIndex = this.storage[index];\n    if (arrayAtIndex) {\n      for (let i = 0; i &lt; arrayAtIndex.length; i++) {\n        const pair = arrayAtIndex[i];\n        if (pair[0] === key) {\n          \/\/ return the value\n          return pair[1];\n        }\n      }\n    }\n  }<\/pre>\n<p>I don\u2019t think there is a need to go through this, as it acts the same as the <code>remove<\/code> method.<\/p>\n<p>This is a great introduction to the hash table, and as you can tell, it is not as complicated as it initially seems. This is a data structure that is used all over the place, so it is a great one to understand!<\/p>\n<h2>Binary search tree<\/h2>\n<p>Sadly (or maybe thankfully), this is the last data structure that we will tackle \u2014 the notorious binary search tree.<\/p>\n<p>When we think of a binary search tree, the three things we should think of are:<\/p>\n<ul>\n<li><strong>Root:<\/strong> This is the very top node of a tree structure and does not have a parent<\/li>\n<li><strong>Parent:<\/strong> It is a child of a node but also the parent of a node<\/li>\n<li><strong>Child:<\/strong> This node is the child of a node and does not necessarily have a child<\/li>\n<\/ul>\n<p>In a binary search tree, each node either has zero, one, or two children. The child on the left is called the left child, and the child on the right is the right child. In a binary search tree, the child on the left must be smaller than the child on the right.<\/p>\n<p>Visually, you can picture a binary search tree like so:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-9439\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/binary-search-tree-visual.png\" alt=\"Visual Representation Of A Binary Search Tree\" width=\"730\" height=\"679\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/binary-search-tree-visual.png 730w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/binary-search-tree-visual-300x279.png 300w\" sizes=\"auto, (max-width: 730px) 100vw, 730px\" \/><\/p>\n<p>The core class for a tree would look like this:<\/p>\n<pre>class Tree {\n   constructor(value) {\n     this.root = null\n   }\n\n   add(value) {\n<em>    \/\/ we'll implement this below<\/em>\n   }\n\n}<\/pre>\n<p>We\u2019ll also create a <code>Node<\/code> class to represent each of our nodes.<\/p>\n<pre>class Node {\n  constructor(value, left = null, right = null) {\n    this.value = value;\n    this.left = left;\n    this.right = right;\n  }\n}<\/pre>\n<p>OK, let\u2019s implement the <code>add<\/code> method. I have commented in the code, but if you find it confusing, just remember that all we are doing is going from our root and checking the <code>left<\/code> and <code>right<\/code> of each node.<\/p>\n<pre>add(value) {\n    Let newNode = new Node(value);\n<em>    \/\/ if we do not have a root, then we create one<\/em>\n    if (this.root === null) {\n      this.root = newNode;\n      return this;\n    }\n    let current = this.root;\n<em>    \/\/ while we have a node<\/em>\n    while (current) {\n      <span style=\"font-weight: 400;\">if(value === current.value) return undefined;<\/span>\n<em>      \/\/ go left if our current value is greater\n      \/\/ than the value passed in<\/em>\n      if (current.value &gt; value) {\n<em>        \/\/ if there is a left child, then run the\n        \/\/ loop again<\/em>\n        if (current.left) {\n          current = current.left;\n        } else {\n          current.left = newNode;\n          return this;\n        }\n      }\n<em>      \/\/ the value is smaller, so we go right<\/em>\n      else {\n<em>        \/\/ go right\n        \/\/ if there is a left child, then run the\n        \/\/ loop again<\/em>\n        if (current.right) {\n          current = current.right;\n        } else {\n          current.right = newNode;\n          return this;\n        }\n      }\n    }\n}\n<\/pre>\n<p>Let\u2019s test our new <code>add<\/code> method like so:<\/p>\n<pre>const t = new Tree();\nt.add(2);\nt.add(5);\nt.add(3);<\/pre>\n<p>Our tree now looks like the following:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-54947\" src=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/binary-search-tree-code-example-1.png\" alt=\"javascript data structure binary search tree code\" width=\"700\" height=\"482\" srcset=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/binary-search-tree-code-example-1.png 700w, https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/binary-search-tree-code-example-1-300x207.png 300w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/><\/p>\n<p>So to get an even better understanding, let\u2019s implement a method that checks if our tree contains a value.<\/p>\n<pre>contains(value) {\n<em>  \/\/ get the root<\/em>\n  let current = this.root;\n<em>  \/\/ while we have a node<\/em>\n  while (current) {\n<em>    \/\/ check if our current node has the value<\/em>\n    if (value === current.value) {\n      return true; <em>\/\/ leave the function<\/em>\n    }\n    <em>\/\/ we decide on the next current node by comparing our value<\/em>\n<em>    \/\/ against current.value - if its less go left else right<\/em>\n    current = value &lt; current.value ? current.left : current.right;\n  }\n  return false;\n}<\/pre>\n<p><code>Add<\/code> and <code>Contains<\/code> are the two core methods of the binary search tree. An understanding of both these methods give you better perspective on how you would tackle problems at your day-to-day job.<\/p>\n<h2>Conclusion<\/h2>\n<p>Wow, this was a long one. We have covered a lot of material in this article, and it will greatly assist you in technical interviews. I really hope you learned something (I know I have) and that you will feel more comfortable approaching technical interviews (especially the nasty white-boarding ones).<\/p>\n<\/html>\n","protected":false},"excerpt":{"rendered":"<p>A strong grasp of JavaScript data structures could help you ace your next interview and perform better in your day-to-day job.<\/p>\n","protected":false},"author":156415413,"featured_media":9626,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2147999,1],"tags":[2109821],"class_list":["post-9379","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-dev","category-uncategorized","tag-vanilla-javascript"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.1.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Know your JavaScript data structures - LogRocket Blog<\/title>\n<meta name=\"description\" content=\"Data structures are often overlooked in JavaScript, but understanding them can help you perform better in your day-to-day job.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Know your JavaScript data structures - LogRocket Blog\" \/>\n<meta property=\"og:description\" content=\"Data structures are often overlooked in JavaScript, but understanding them can help you perform better in your day-to-day job.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/\" \/>\n<meta property=\"og:site_name\" content=\"LogRocket Blog\" \/>\n<meta property=\"article:published_time\" content=\"2021-06-04T13:00:25+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-06-04T21:20:03+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/know-your-javascript-data-structures-nocdn.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"730\" \/>\n\t<meta property=\"og:image:height\" content=\"487\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Paul Ryan\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/PaulRyan7\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Paul Ryan\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"16 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/\",\"url\":\"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/\",\"name\":\"Know your JavaScript data structures - LogRocket Blog\",\"isPartOf\":{\"@id\":\"https:\/\/blog.logrocket.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/know-your-javascript-data-structures-nocdn.jpg\",\"datePublished\":\"2021-06-04T13:00:25+00:00\",\"dateModified\":\"2024-06-04T21:20:03+00:00\",\"author\":{\"@id\":\"https:\/\/blog.logrocket.com\/#\/schema\/person\/b31ae53d8e24625b09b1d60a93900881\"},\"description\":\"Data structures are often overlooked in JavaScript, but understanding them can help you perform better in your day-to-day job.\",\"breadcrumb\":{\"@id\":\"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/#primaryimage\",\"url\":\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/know-your-javascript-data-structures-nocdn.jpg\",\"contentUrl\":\"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/know-your-javascript-data-structures-nocdn.jpg\",\"width\":730,\"height\":487,\"caption\":\"Know Your JavaScript Data Structures\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/blog.logrocket.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Know your JavaScript data structures\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/blog.logrocket.com\/#website\",\"url\":\"https:\/\/blog.logrocket.com\/\",\"name\":\"LogRocket Blog\",\"description\":\"Resources to Help Product Teams Ship Amazing Digital Experiences\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/blog.logrocket.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/blog.logrocket.com\/#\/schema\/person\/b31ae53d8e24625b09b1d60a93900881\",\"name\":\"Paul Ryan\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/blog.logrocket.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/183fe9fe85c475243fc0d65b444abf265a7e2b37a000f87cf1119274f71c1950?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/183fe9fe85c475243fc0d65b444abf265a7e2b37a000f87cf1119274f71c1950?s=96&d=mm&r=g\",\"caption\":\"Paul Ryan\"},\"description\":\"Developer hailing from Ireland. Loves all things JS and also starting to fall in love with SVGs!\",\"sameAs\":[\"http:\/\/paulryancv.com\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/PaulRyan7\"],\"url\":\"https:\/\/blog.logrocket.com\/author\/paulryan\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Know your JavaScript data structures - LogRocket Blog","description":"Data structures are often overlooked in JavaScript, but understanding them can help you perform better in your day-to-day job.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/","og_locale":"en_US","og_type":"article","og_title":"Know your JavaScript data structures - LogRocket Blog","og_description":"Data structures are often overlooked in JavaScript, but understanding them can help you perform better in your day-to-day job.","og_url":"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/","og_site_name":"LogRocket Blog","article_published_time":"2021-06-04T13:00:25+00:00","article_modified_time":"2024-06-04T21:20:03+00:00","og_image":[{"width":730,"height":487,"url":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/know-your-javascript-data-structures-nocdn.jpg","type":"image\/jpeg"}],"author":"Paul Ryan","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/PaulRyan7","twitter_misc":{"Written by":"Paul Ryan","Est. reading time":"16 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/","url":"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/","name":"Know your JavaScript data structures - LogRocket Blog","isPartOf":{"@id":"https:\/\/blog.logrocket.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/#primaryimage"},"image":{"@id":"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/#primaryimage"},"thumbnailUrl":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/know-your-javascript-data-structures-nocdn.jpg","datePublished":"2021-06-04T13:00:25+00:00","dateModified":"2024-06-04T21:20:03+00:00","author":{"@id":"https:\/\/blog.logrocket.com\/#\/schema\/person\/b31ae53d8e24625b09b1d60a93900881"},"description":"Data structures are often overlooked in JavaScript, but understanding them can help you perform better in your day-to-day job.","breadcrumb":{"@id":"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/#primaryimage","url":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/know-your-javascript-data-structures-nocdn.jpg","contentUrl":"https:\/\/blog.logrocket.com\/wp-content\/uploads\/2019\/11\/know-your-javascript-data-structures-nocdn.jpg","width":730,"height":487,"caption":"Know Your JavaScript Data Structures"},{"@type":"BreadcrumbList","@id":"https:\/\/blog.logrocket.com\/know-your-javascript-data-structures\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/blog.logrocket.com\/"},{"@type":"ListItem","position":2,"name":"Know your JavaScript data structures"}]},{"@type":"WebSite","@id":"https:\/\/blog.logrocket.com\/#website","url":"https:\/\/blog.logrocket.com\/","name":"LogRocket Blog","description":"Resources to Help Product Teams Ship Amazing Digital Experiences","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/blog.logrocket.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/blog.logrocket.com\/#\/schema\/person\/b31ae53d8e24625b09b1d60a93900881","name":"Paul Ryan","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/blog.logrocket.com\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/183fe9fe85c475243fc0d65b444abf265a7e2b37a000f87cf1119274f71c1950?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/183fe9fe85c475243fc0d65b444abf265a7e2b37a000f87cf1119274f71c1950?s=96&d=mm&r=g","caption":"Paul Ryan"},"description":"Developer hailing from Ireland. Loves all things JS and also starting to fall in love with SVGs!","sameAs":["http:\/\/paulryancv.com\/","https:\/\/x.com\/https:\/\/twitter.com\/PaulRyan7"],"url":"https:\/\/blog.logrocket.com\/author\/paulryan\/"}]}},"yoast_description":"Data structures are often overlooked in JavaScript, but understanding them can help you perform better in your day-to-day job.","_links":{"self":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts\/9379","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/users\/156415413"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/comments?post=9379"}],"version-history":[{"count":30,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts\/9379\/revisions"}],"predecessor-version":[{"id":59482,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/posts\/9379\/revisions\/59482"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/media\/9626"}],"wp:attachment":[{"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/media?parent=9379"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/categories?post=9379"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.logrocket.com\/wp-json\/wp\/v2\/tags?post=9379"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}