Basic Data Structure In Javascript

Here we go again to understand how to analyze javascript array methods push() and pop() to Stack . Let's understand this from a life scenario before implementing and comparing it to array methods. The stack operation is LAST IN FIRST OUT (LIFO) and can be practiced in a real-life scenario using a stack of bread as a demo.The operations means, the last item added to the stack is the first item to be removed.

stack-sliced-bread-plate-11241443.jpg

  • in the above image of bread, I'm going to explain how LIFO operates.*

    A loaf of bread contains six slices arranged on top of each other, so where LIFO comes to play here is that the last bread added to the stack is going to be removed first. Moving to implement the stack operation using javascript with a diagram of an array before code example, push and pop array methods perform an opposite operation, push is used to add an item to an array and pops remove item from a stack or an array

qMSmxsa.png In the above diagram, we have three items in the starting stack which contains [1,2,3], moving to the second stage, a new item (4) was added(push) which increase the length of the array and the new stack is [1,2,3,4] and serves as the LAST IN on the stack. To the third diagram, we removed(pop) an item with pop() which deletes the last item (FIRST OUT) in the stack and the length of the array also changes back to the starting stack.

CODE SAMPLE

var stack=[ 'stack1', 'stack2' ]
var addNewStack=[ 'stack3' ]
stack.push(addNewStack) //adding stack3 and stack4 to the stack array.
console.log(stack)//[ 'stack1', 'stack2' , 'stack3' ]

Note: stack3 is the last item we passed into the array.

stack.pop()//remove the last item which is the first out of the array
console.log(stack)//[ 'stack1', 'stack2']

In conclusion, I have been able to explain how the stack works, the operations carried out by stack, how we use the push and pop javascript array method regarding data structure, and a life scenario experiment using a loaf of bread as a demo.

Let's connect on social media for more insightful articles Twitter:twitter.com/AdeyemiBuhari3

Linkedin:linkedin.com/in/adeyemi-buhari-3aa4781b5