Verifying whether the stack is empty

The next method we will create is the isEmpty method, which returns true if the stack is empty (no element has been added), and false otherwise:

isEmpty() {  return this.items.length === 0;} 

Using the isEmpty method, we can simply verify whether the length of the internal array is 0.

Similar to the length property from the array class, we can also implement length for our Stack class. For collections, we usually use the term size instead of length. And again, as we are using an array to store the elements internally, we can simply return its length:

size() {  return this.items.length;} 

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.