- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Clearing the elements of a Stack in Javascript
Consider a simple stack class in Javascript.
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); } pop() { // Check if empty if (this.isEmpty()) { console.log("Stack Underflow!"); return; } this.container.pop(); } peek() { if (isEmpty()) { console.log("Stack Underflow!"); return; } return this.container[this.container.length - 1]; } }
Here the isFull function just checks if the length of a container is equal to or more than maxSize and returns accordingly. The isEmpty function checks if a size of the container is 0. The Push and Pop functions are used to add and remove new elements from the stack respectively.
In this section, we are going to add CLEAR operation in this class. We can clear the contents just by reassigning the container element to an empty array. For example,
Example
clear() { this.container = []; }
You can check if this function is working fine using −
Example
let s = new Stack(2); s.push(10); s.push(20); s.display(); s.clear(); s.display();
Output
This will give the output −
[10, 20] []
- Related Articles
- Clearing the elements of the Queue in Javascript
- Clearing the elements of the PriorityQueue using Javascript
- Pushing elements to a Stack in Javascript
- Popping elements from a Stack in Javascript
- Peeking elements from a Stack in Javascript
- Sorting elements of stack using JavaScript
- Clearing localStorage in JavaScript?
- Clearing a Dictionary using Javascript
- Clearing the set using Javascript
- Not able to push all elements of a stack into another stack using for loop in JavaScript?
- Creating a Stack in Javascript
- Implementation of Stack in JavaScript
- The Stack Class in Javascript
- Get the number of elements contained in the Stack in C#
- Check if the elements of stack are pairwise sorted in Python

Advertisements