Queues and Stacks in Javascript Data Structures


Published on 19 April 2022


Queues and Stacks in Javascript Data Structures

 

Queues and Stacks. They are abstract data structures that store values in a collection, whose utility is in the fact that these values can be added or extracted.
The difference between a queue and a stack is the order of fetching an element from the data structure.

  • Stack. Your data is stored in column form, that is, the data added last at the top of this column is the one that can be removed.
    stack image.  Methods used: 
    • push(): adding the data
    • pop(): removing data

<script type="text/javascript">
  const mystack = [];
  console.log('Adding John'+mystack.push('John'));
  console.log('Adding Albert'+mystack.push('Albert'));
   console.log('Adding Robert'+mystack.push('Robert'));
  console.log(mystack.length);//3
  console.log(mystack.pop());//['Robert']
  console.log(mystack);//['John', 'Albert']
</script>   

[Robert→Albert→John]

  • Queue. The data is stored in the form of a column, adding the data in the initial part, and being able to withdraw the data only from the final part of the column.
    tail image. Methods used:
    • push(): adding the data
    • shift(): removing data

<script type="text/javascript">
  const myqueue = [];
  console.log(myqueue.push('John'));
  console.log(myqueue.push('Albert'));
  console.log(myqueue.push('Robert'));
  console.log(myqueue);// ['John', 'Albert', 'Robert']
  console.log(myqueue[0]);//John
  console.log(myqueue[myqueue.length-1]);//Robert
  console.log(myqueue.shift());//Deleted John
  console.log(myqueue);//['Albert', 'Robert']
</script>    



Tips on SEO and Online Business

Next Articles

Previous Articles