- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pushing elements to a Stack in Javascript
Consider the following stack class in Javascript with few small helper functions.
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; } }
Here the isFull function just checks if the length of container is equal to or more than maxSize and returns accordingly. The isEmpty function checks if size of the container is 0.
In this section, we are going to add PUSH operation in this class. Pushing elements to a Stack means adding them to the top of the array. We are taking the end of the container array to be the top of the array as we'll perform all operations with respect to it. So we can implement the push function as follows −
Example
push(element) { // Check if stack is full if (this.isFull()) { console.log("Stack Overflow!"); return; } this.container.push(element); }
You can check if this function is working fine using −
Example
let s = new Stack(2); s.display(); s.push(10); s.push(20); s.push(30); s.display();
Output
This will give the output −
[] Stack Overflow! [ 10, 20 ]
- Related Articles
- Popping elements from a Stack in Javascript
- Peeking elements from a Stack in Javascript
- Clearing the elements of a Stack in Javascript
- Pushing false objects to bottom in JavaScript
- Sorting elements of stack using JavaScript
- Not able to push all elements of a stack into another stack using for loop in JavaScript?
- Pushing positives and negatives to separate arrays in JavaScript
- Pushing NaN to last of array using sort() in JavaScript
- Creating a Stack in Javascript
- Stack Data Structure in Javascript
- The Stack Class in Javascript
- Implementation of Stack in JavaScript
- Prefix calculator using stack in JavaScript
- How to set the stack order of a positioned element in JavaScript?
- How to reverse the elements of an array using stack in java?

Advertisements