w3resource

JavaScript Exercises: Remove all the elements from a given stack

JavaScript Stack: Exercise-6 with Solution

Clear Stack

Write a JavaScript program to remove all elements from a given stack.

Sample Solution:

JavaScript Code:

class Stack {
  constructor() {
    this.items = [];
  }

  push(element) {
    this.items.push(element);
  }

  pop() {
    if (this.isEmpty())
      return "Underflow";
    return this.items.pop();
  }

  peek() {
    if (this.isEmpty())
      return "No elements in Stack";
    return this.items[this.items.length - 1];
  }

  isEmpty() {
    return this.items.length === 0;
  }
  clear() {
    this.items = [];
  }
 // Returns the number of elements in the stack
 size() {
    return this.items.length;
  }  

displayStack(stack) {
  console.log("Stack elements are:");
  let str = "";
  for (let i = 0; i < stack.items.length; i++)
    str += stack.items[i] + " ";
  return str.trim();
 }        
}
console.log("Initialize a stack:")
let stack = new Stack();
console.log("Is the stack empty?");
console.log(stack.isEmpty()); 
console.log("Input some elements on the stack:")
stack.push(1);
stack.push(4);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(6); 
console.log(stack.displayStack(stack));
console.log("Remove all the elements from the said stack:")
stack.clear();
console.log("Is the stack empty?");
console.log(stack.isEmpty());

Sample Output:

Initialize a stack:
Is the stack empty?
true
Input some elements on the stack:
Stack elements are:
1 4 3 2 5 6
Remove all the elements from the said stack:
Is the stack empty?
true

Flowchart:

Flowchart: JavaScript  Exercises: Remove all the elements from a given stack.
Flowchart: JavaScript  Exercises: Remove all the elements from a given stack.

Live Demo:

See the Pen javascript-stack-exercise-5 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that empties a stack by setting its length property to zero and returns the cleared stack.
  • Write a JavaScript function that pops all elements from a stack one by one and logs each popped value.
  • Write a JavaScript function that clears a stack implemented as a linked list by severing its head pointer.
  • Write a JavaScript function that empties a stack and verifies the operation by checking if isEmpty() returns true.

Go to:


PREV : Max & Min in Stack.
NEXT : Count Stack Elements.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.