Custom Search

JavaScript Tutorial - Implementing Stack Object in JavaScript

Stack acts as a temporary data storage using LIFO(Last In First Out) principle. Stack can perform two basic operation PUSH and POP. Push operation adds an data to the top of the stack and all the remaining data below it. Pop operation removes and returns the current data on the top node of the stack. Below is the code snippet in JavaScript to perform Stack Operation using Objects.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<script type="text/javascript">
    function Stack()	//Creating Stack Object
    {
        // Create an empty array of cards.
        this.cards = new Array();  //cards array inside stack object
        this.push  = pushdata;      //Call pushdata function on push operation
        this.pop   = popdata;	     //Call popdata function on pop operation
        this.printStack = showStackData; //Call showStackData function on printstack operation
    }
 
    function pushdata(data)
    {
        this.cards.push(data);
    }
 
    function popdata(data)
    {
        return this.cards.pop();			
    }
 
    function showStackData()
    {
        return this.cards;
    }
 
    var a = new Stack();	//Create stack Object
    a.push(12);		//Push Data onto Stack
    a.push(32);
    a.push(42);
    var z = a.pop();
    document.write("Data Popped: " + z);
    document.write("Stack Output: " + a.printStack());
</script>

Output:
Data Popped: 42
Stack Output: 12,32
Explanation:

Custom Search

Related Post

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)