title: JavaScript Linked Stack
body: <p>I am practicing data structures on JavaScript, and wrote a stack based linked list. However, three of my methods <code>pop()</code> <code>peek()</code> and <code>toString()</code> are faulty because they return undefined values, whereas I would like them to return the numerical values.
  The rest of the stack methods are working fine! Could this be a scoping issue? Thank you for your time and help.</p>
  <p>Updated working code is below after the comment suggestions!</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 {
      /* Creates a node with the given element and next node */
      constructor(e, n) {
          this.data = e;
          this.next = n;
      }
  }
  
  class LinkedStack {
      /* Creates an empty stack */
      constructor() {
          this.top = null;
          this.size = 0;
      }
  
      push = (elem) =&gt; {
          let v = new Node(elem, this.top);
          this.top = v;
          this.size++;
      }
  
      length = () =&gt; {
          return this.size;
      }
  
      isEmpty = () =&gt; {
          return this.size === 0;
      }
  
      peek = () =&gt; {
          if (this.isEmpty()) {
              console.log("Empty Stack");
          }
          return this.top.data;
      }
  
      pop = () =&gt; {
          if (this.isEmpty()) {
              console.log("Empty Stack");
          }
          const temp = this.top.data;
          this.top = this.top.next;
          this.size--;
          return temp;
      }
  
      toString = () =&gt; {
          let s = "[";
          let cur = null;
          if (this.length() &gt; 0) {
              cur = this.top;
              s += cur.data;
          }
  
          if (this.length() &gt; 1) {
              for (let i = 1; i &lt;= this.length() - 1; i++) {
                  cur = cur.next;
                  s += ", " + cur.data;
              }
              s += "]";
              return s;
          }
      }
  }
  
  let stack = new LinkedStack();
  stack.push(9);
  console.log(stack.pop() + " was popped"); // undefined, but stack size decreases
  stack.push(12);
  stack.push(15);
  console.log("Is Stack Empty? " + stack.isEmpty());
  console.log("Stack Length: " + stack.length());
  console.log("Top value: " + stack.peek());
  console.log("Stack Content: " + stack.toString()); // Stack content [15, undefined]</code></pre>
  </div>
  </div>
  </p>