Home > Javascript > Implementing Stack Object in JavaScript

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:

  • Here i am creating Stack Object in JavaScript using Template Based Object Creation. Internally the stack objects has an Array Object called cardsthat will hold the data stored inside the stack.
  • The stack objects also holds the function call for methods getting called
  • Referring to line 26 i am creating a new object of Stack
  • Referring to line 27, 28, 29, 30 i am calling the methods defined for the Stack Object
  • Pop methods returns the popped element from array so referring to 30 variable z holds the popped data


Custom Search

Popular Articles:

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • IndianPad
  • LinkedIn
  • Live
  • MySpace
  • Netvibes
  • RSS
  • Technorati
  • Yahoo! Bookmarks
  • Yahoo! Buzz
  • Reddit
  • Add to favorites
  • PDF
  • Twitter
Categories: Javascript Tags:
  1. January 11th, 2010 at 06:17 | #1

    I think there is a typo on line 16. I don’t see why the popData method takes a parameter of “data”?

    It looks like it should just be:
    function popdata()
    {
    return this.cards.pop();
    }

  2. Ravi
    May 20th, 2010 at 23:41 | #2

    Just wondering isnt the Array object in itself a stack data structure ? Your implementation seems to create a wrapper around Array Object without adding any functionality

  1. No trackbacks yet.