title: TypeError: Cannot read property 'data' of undefined - but it is defined
body: <p>I am working on a binary search tree algorithm and for some reason, I keep getting a type error. It always occurs when a second value is being inserted into the tree. Specifically when the current node's value is being compared to the incoming data value</p>
  
  <p>Here's the code: </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>class Node {
      constructor(data, left = null, right = null) {
          this.data = data;
          this.leftNode = left;
          this.rightNode = right;
      }
  }
  
  class BST {
      constructor() {
          this.root = null;
      }
      insert(data) {
          const dataNode = new Node(data);
          if (this.root === null) {
              this.root = dataNode;
          } else {
              let currentNode = this.root;
              let parentNode;
              while (true) {
                  parentNode = currentNode;
                  if (data &lt; currentNode.data) {
                      currentNode = parentNode.left;
                      if (parentNode.left === null) {
                          parentNode.left = dataNode
                          break;
                      }
                  } else {
                      currentNode = parentNode.right
                      if (parentNode.right === null) {
                          parentNode.right = dataNode
                          break;
                      }
                  }
              }
          }
      }
  }
  const bst = new BST();
  
  bst.insert(10);
  bst.insert(5);
  bst.insert(6);
  bst.insert(8);
  bst.insert(12);
  bst.insert(7);
  bst.insert(7);</code></pre>
  </div>
  </div>
  </p>
  
  <p>Here's the error: </p>
  
  <pre><code>Uncaught TypeError: Cannot read property 'data' of undefined
      at BST.insert (&lt;anonymous&gt;:22:32)
      at &lt;anonymous&gt;:42:5
  </code></pre>