Stack:
Javascript is a single-threaded language, which means it will use a single call stack to manage execution context.
- Whenever function is called, then javascript engine will create a global execution context in call stack, on top of global execution context it will create a function context in the same call stack.
- call-stack follows last in first out order(LIFO) to pop off the execution context from the call stack.
Example of stack data structure:
Note: Execute below code in java script compiler and check the console output.
var Stack=function(){
this.count=0;
this.storage={};
this.size=function(){
return this.count;
}
this.push=function(item){
this.storage[this.count]=item;
this.count++;
}
this.peek=function(){
return this.storage[this.count-1]
}
this.pop=function(){
if(this.count==0){
return undefined;
}
this.count--;
var result=this.storage[this.count]
delete this.storage[this.count]
return result;
}
}
var stack=new Stack();
console.log(stack.size())
stack.push(1);
stack.push(2);
console.log(stack.size())
console.log(stack.peek())
console.log(stack.pop())
console.log(stack.size())
console.log(stack.peek())
Any comments or suggestions are welcome.
Top comments (0)