FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
Implement a stack data structure in JavaScript. A stack is a collection that follows the Last-In-First-Out (LIFO) principle. Your stack should have the following methods:
push(element): Adds an element to the top of the stack.
pop(): Removes the top element from the stack and returns it. Returns undefined if the stack is empty.
peek(): Returns the top element of the stack without removing it. Returns undefined if the stack is empty.
isEmpty(): Returns true if the stack is empty, otherwise returns false.
size(): Returns the number of elements in the stack.
Use the following example to understand how the stack should work:
class Stack {
// Your implementation here
}
const stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.peek()); // 2
console.log(stack.pop()); // 2
console.log(stack.size()); // 1
console.log(stack.isEmpty()); // false
stack.pop();
console.log(stack.isEmpty()); // true
Template
index.js
class Stack {
}
export { Stack };
index.test.js
import { Stack } from './index';
describe('Stack class', () => {
let stack;
beforeEach(() => {
stack = new Stack();
});
test('should push elements to the stack', () => {
stack.push(1);
stack.push(2);
expect(stack.size()).toBe(2);
expect(stack.peek()).toBe(2);
});
test('should pop elements from the stack', () => {
stack.push(1);
stack.push(2);
expect(stack.pop()).toBe(2);
expect(stack.size()).toBe(1);
expect(stack.pop()).toBe(1);
expect(stack.size()).toBe(0);
});
test('should return undefined when popping from an empty stack', () => {
expect(stack.pop()).toBe(undefined);
});
test('should peek the top element without removing it', () => {
stack.push(1);
stack.push(2);
expect(stack.peek()).toBe(2);
expect(stack.size()).toBe(2);
});
test('should return undefined when peeking an empty stack', () => {
expect(stack.peek()).toBe(undefined);
});
test('should check if the stack is empty', () => {
expect(stack.isEmpty()).toBe(true);
stack.push(1);
expect(stack.isEmpty()).toBe(false);
});
test('should return the correct size of the stack', () => {
expect(stack.size()).toBe(0);
stack.push(1);
stack.push(2);
expect(stack.size()).toBe(2);
});
});
Info
Question
Implement a stack data structure in JavaScript. A stack is a collection that follows the Last-In-First-Out (LIFO) principle. Your stack should have the following methods:
push(element)
: Adds an element to the top of the stack.pop()
: Removes the top element from the stack and returns it. Returnsundefined
if the stack is empty.peek()
: Returns the top element of the stack without removing it. Returnsundefined
if the stack is empty.isEmpty()
: Returnstrue
if the stack is empty, otherwise returnsfalse
.size()
: Returns the number of elements in the stack.Use the following example to understand how the stack should work:
Template
index.js
index.test.js