Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
JavaScript Linked Stack

I am practicing data structures on JavaScript, and wrote a stack based linked list. However, three of my methods pop() peek() and toString() 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.

Updated working code is below after the comment suggestions!

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) => {
        let v = new Node(elem, this.top);
        this.top = v;
        this.size++;
    }

    length = () => {
        return this.size;
    }

    isEmpty = () => {
        return this.size === 0;
    }

    peek = () => {
        if (this.isEmpty()) {
            console.log("Empty Stack");
        }
        return this.top.data;
    }

    pop = () => {
        if (this.isEmpty()) {
            console.log("Empty Stack");
        }
        const temp = this.top.data;
        this.top = this.top.next;
        this.size--;
        return temp;
    }

    toString = () => {
        let s = "[";
        let cur = null;
        if (this.length() > 0) {
            cur = this.top;
            s += cur.data;
        }

        if (this.length() > 1) {
            for (let i = 1; i <= 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]

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!