Stacked JavaScript data structure

Compared with an array, a stack is a data structure with more restrictions.

We can only add items to the stack before we can add them to the stack. And we can only delete items at the top of the stack.

Think about it like a pile of books. You can only add books at the top, and you can only delete books at the top.

Therefore, if you add a bunch of books and then want to access the first book you added, you first need to delete all the books until you find the added book.

This concept is called First In First Out (FILO)

Although arrays in JavaScript are built-in and we don't need to build them, we must implement stacks.

We will create a data structure to encapsulate our data, making it inaccessible from the outside, and we will only allowpush()Methods to add data to the stack, andpop()Method of deleting data from the stack.

We can do this in many different ways. One way is to use classes, especially I want to usePrivate class area. Private class fields are not part of the JavaScript standardhowever, But since version 12, they are available in Chrome, Edge, Safari and Node.js. Still hope that it will not be available in Firefox in the near future.

Why should I use them? Because they allow us to very easily encapsulate the internal state of the class and protect it from the outside.

class Stack {
  #items = []
  push = (element) => this.#items.push(element)
  pop = () => this.#items.pop()
  isempty = () => this.#items.length === 0
  empty = () => (this.#items.length = 0)
  size = () => this.#items.length
}

We have 5 public methods:pushwithpopAdd/remove from the stack,isemptyCheck if the stack is empty,emptyClear the stack,sizeGet the stack size.

Now, we can create a stack object from this class and process it:

const stack = new Stack()
stack.push(1)
stack.push(2)
stack.push(3)
console.log(stack.size()) //3
console.log(stack.pop()) //[ 3 ]
console.log(stack.size()) //2

For public property, everything will work in the same way:

class Stack {
  items = []
  push = (element) => this.items.push(element)
  pop = () => this.items.pop()
  isempty = () => this.items.length === 0
  empty = () => (this.items.length = 0)
  size = () => this.items.length
}

Except now we can checkitemsFrom the outside:

const stack = new Stack()
stack.push(2)
console.log(stack.items) //[ 2 ]

When using private class attributes, accessstack.itemsWill be backundefined.

Download mine for freeJavaScript beginner's manual


More js tutorials: