Skip to Content
Author's profile photo Amol Gupta

Code exercise : Implementing a Stack in Javascript

Introduction : While programming with SAPUI5 one has to do quite some Javascript programming too. Here is a code exercise with solution to get your hands dirty.
Target Audience : Beginners
Prerequisites : You should know what is a Stack and some Javascript. If not use the Hints section.
Date created : 20.10.2016
Note for the audience : Any suggestions are most welcome and will be accomodated

Challenge question : Implement a stack with Javascript Objects. Give it shot on your own without jumping to the solution right away.

Hints :

Learn basics of Javascript https://www.codecademy.com/learn/javascript

Learn what is a stack https://en.wikipedia.org/wiki/Stack_(abstract_data_type)

Interesting to note :

Javascript programming can be done in the Console tab of the Chrome browser.

push() and pop() methods are also inbuilt methods that can be called on an array.

In Javascript we dont have int, float, double etc. All variables are a var.

Disclaimer : On a lighter note, I do not claim that this is the best or the only possible implementation of Stack.

Potential Solution :

function Stack(top) {
	this.top = top;
	this.arr = [];
	this.push= function(x){
		if (this.arr.length<this.top){
			this.arr.push(x);
			console.log("Push successful");
		} 
		else console.log("Stack full");
	};
	this.pop = function(){
		if (this.arr.length > 0) {
			console.log("Pop successful");
			return this.arr.pop();
		}
		else console.log("Stack empty");
	};
	this.display = function()
	{
		console.log("Thats our array : " + this.arr);
	};
	this.size = function ()
	{
		console.log("Size of this Stack is : " + this.arr.length);
	}
}

var s = new Stack (5);

s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
s.display();
s.size();
s.pop();

Of course you can try out some method calls on your own.

Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.