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 188 views
1 answer 159 views
1 answer 177 views
1 answer 175 views
1 answer 172 views
1 answer 189 views
...