

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Creating a Stack in Javascript
Though Arrays in JavaScript provide all the functionality of a Stack, let us implement our own Stack class. Our class will have the following functions −
- push(element): Function to push elements on top of the stack.
- pop(): Function that removes an element from the top and returns it.
- peek(): Returns the element on top of the stack.
- isFull(): Checks if we reached the element limit on the stack.
- isEmpty(): checks if the stack is empty.
- clear(): Remove all elements.
- display(): display all contents of the array
Let's start by defining a simple class with a constructor that takes the max size of the stack and a helper function display() that'll help us when we implement the other functions for this class. We have also defined 2 more functions, isFull and isEmpty to check if the stack is full or empty.
The isFull function just checks if the length of the container is equal to or more than maxSize and returns accordingly.
The isEmpty function checks if a size of the container is 0.
These will be helpful when we define other operations. The functions we define from this point onwards will all go inside the Stack class.
Example
class Stack { constructor(maxSize) { // Set default max size if not provided if (isNaN(maxSize)) { maxSize = 10; } this.maxSize = maxSize; // Init an array that'll contain the stack values. this.container = []; } // A method just to see the contents while we develop this class display() { console.log(this.container); } // Checking if the array is empty isEmpty() { return this.container.length === 0; } // Check if array is full isFull() { return this.container.length >= maxSize; } push(element) { // Check if stack is full if (this.isFull()) { console.log("Stack Overflow!"); return; } this.container.push(element); } }
- Related Questions & Answers
- Creating a Queue in Javascript
- Creating a Graph in Javascript
- Creating a Set using Javascript
- Creating a BinaryTree using Javascript
- Pushing elements to a Stack in Javascript
- Popping elements from a Stack in Javascript
- Peeking elements from a Stack in Javascript
- Creating a chained operation class in JavaScript
- Stack Data Structure in Javascript
- The Stack Class in Javascript
- Implementation of Stack in JavaScript
- Creating a Priority Queue using Javascript
- Creating a linked list using Javascript
- Creating a hash table using Javascript
- JavaScript - Creating a Custom Image Slider