Creating the toString method

In the array version, we do not need to worry about a toString method because the data structure will use the one already provided by the array. For this object version, we will create a toString method so we can print the content of the stack similar to an array:

toString() {  if (this.isEmpty()) {    return '';  }  let objString = `${this.items[0]}`; // {1}  for (let i = 1; i < this.count; i++) { // {2}    objString = `${objString},${this.items[i]}`; // {3}  }  return objString;}

If the stack is empty, we simply return an empty string. If it is not empty, we will initialize the string with the first element, from the base of the stack ({1}). Then, we will iterate through all the keys of the stack ({2}) until its top, adding ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.