Stack in Javascript(ES5)

Nishit Ranjan
1 min readJan 22, 2020

//creating a functional constructor

function Stack(){

//the data structure for stack
let items = [];

//adding new elements to the stack
this.push = function(elem){
return items.push(elem)
}
this.pop = function(){
return items.pop()
};
//will return elements at top of the stack
this.peek = function(){
return items[items.length-1]
}

//checking if the stack isEmpty
this.isEmpty= function(){
return items.length ===0
}

//checking the size of stack
this.size = function(){
return items.length
};

//printing the elements in stack
this.print=function(){
return items.toString()
}
}

Implementation of Stack:

let stack = new Stack();
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(‘a’);

stack.print()
stack.size()
stack.peek();
stack.isEmpty()

--

--

Nishit Ranjan
0 Followers

I am a software engineer. I specialize in JavaScript, React.js, NodeJS, Docker and Kubernetes.