JavaScript Program to Implement a Stack

To understand this example, you should have the knowledge of the following JavaScript programming topics:


The stack is a data structure that follows Last In First Out (LIFO) principle. The element that is added at last is accessed at first. This is like stacking your books on top of each other. The book that you put at last comes first.


Example: Implement Stack

Output

[1, 2, 4, 8]
[1, 2, 4]
4
false
3
[]

In the above program, the Stack class is created to implement the stack data structure. The class methods like add(), remove(), peek(), isEmpty(), size(), clear() are implemented.

An object stack is created using a new operator and various methods are accessed through the object.

  • Here, initially this.items is an empty array.
  • The push() method adds an element to this.items.
  • The pop() method removes the last element from this.items.
  • The length property gives the length of this.items.