Peek returns the top element without removing it from the stack.
If a stack is empty, what should peek return?
AThe first element
BAn error or null/undefined
CThe last element
DThe whole stack
✗ Incorrect
Peeking an empty stack usually returns null, undefined, or an error because there is no top element.
Which data structure principle does stack follow?
ANone of the above
BFirst In, First Out (FIFO)
CRandom Access
DLast In, First Out (LIFO)
✗ Incorrect
Stack follows Last In, First Out (LIFO) principle.
In JavaScript, how do you access the top element of a stack stored as an array named 'stack'?
Astack.pop()
Bstack[0]
Cstack[stack.length - 1]
Dstack.push()
✗ Incorrect
The top element is at index stack.length - 1.
What is the difference between peek and pop in a stack?
APop removes the top element, peek only shows it
BBoth only show the top element
CBoth remove the top element
DPeek removes the top element, pop only shows it
✗ Incorrect
Pop removes and returns the top element, peek only returns it without removing.
Explain how the peek operation works in a stack and why it is useful.
Think about looking at the top book on a stack without taking it off.
You got /3 concepts.
Write a simple JavaScript code snippet to peek the top element of a stack represented by an array.
Use array indexing with length property.
You got /3 concepts.
Practice
(1/5)
1. What does the peek operation do in a stack?
easy
A. Returns the top element without removing it
B. Removes the top element and returns it
C. Adds a new element to the top
D. Checks if the stack is empty
Solution
Step 1: Understand stack operations
A stack stores elements with last-in, first-out order. Peek shows the top element without removing it.
Step 2: Differentiate peek from pop
Pop removes and returns the top element, peek only returns it without removal.
Final Answer:
Returns the top element without removing it -> Option A
Quick Check:
Peek = top element without removal [OK]
Hint: Peek shows top without removing it [OK]
Common Mistakes:
Confusing peek with pop operation
Thinking peek adds elements
Assuming peek checks emptiness
2. Which of the following is the correct syntax to peek the top element of a stack implemented as an array named stack in JavaScript?
easy
A. stack.peek()
B. stack.pop()
C. stack[stack.length - 1]
D. stack.top()
Solution
Step 1: Understand JavaScript array indexing
JavaScript arrays use zero-based indexing. The last element is at index length - 1.
Step 2: Identify correct peek syntax
To peek, access the last element without removing it: stack[stack.length - 1]. stack.pop() removes the element, stack.peek() and stack.top() are not default methods.
Final Answer:
stack[stack.length - 1] -> Option C
Quick Check:
Peek = stack[stack.length - 1] [OK]
Hint: Use stack[stack.length - 1] to peek top [OK]