How to implement a stack using an array in JavaScript

1 Answer

0 votes
// Create a stack
let stack = [];

// Push elements onto the stack
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);

console.log(stack); 

// Pop an element from the stack
let poppedElement = stack.pop();
console.log(poppedElement); 

console.log(stack); 

// Peek at the top element
let topElement = stack[stack.length - 1];
console.log(topElement); 



/*
run:

[ 10, 20, 30, 40, 50 ]
50
[ 10, 20, 30, 40 ]
40

*/

 



answered Aug 14, 2025 by avibootz

Related questions

1 answer 110 views
1 answer 75 views
1 answer 68 views
1 answer 83 views
1 answer 70 views
1 answer 86 views
...