It shows the front element of the queue without removing it, so you can see who is next without changing the queue.
Click to reveal answer
beginner
Why is peek useful in a queue?
Peek lets you check the next item to be processed without changing the order or removing it, like looking at the first person in line without letting them go.
Click to reveal answer
beginner
In a queue implemented with an array, how do you peek the front element?
You look at the element at index 0, because the front of the queue is always the first element in the array.
Click to reveal answer
beginner
What happens if you peek an empty queue?
Usually, you get a special value like null or undefined to show the queue is empty and there is no front element.
Click to reveal answer
beginner
Show the JavaScript code to peek the front element of a queue stored as an array named 'queue'.
D. Using pop() removes the last element instead of peeking the front
Solution
Step 1: Understand pop() behavior on arrays
pop() removes and returns the last element, not the front.
Step 2: Correct way to peek front element
To peek front, access queue[0] without removing it.
Final Answer:
Using pop() removes the last element instead of peeking the front -> Option D
Quick Check:
pop() removes last, not front [OK]
Hint: pop() removes last; peek front uses index 0 [OK]
Common Mistakes:
Using pop() to peek front
Confusing pop() with shift()
Trying to push in peek function
5. You have a queue implemented as an array: let q = [100, 200, 300]. You want to peek the front element safely, but the queue might be empty sometimes. Which code snippet correctly peeks the front element without causing an error?
hard
A. console.log(q.pop());
B. console.log(q[0]);
C. console.log(q.length > 0 ? q[0] : 'Queue is empty');
D. console.log(q.shift());
Solution
Step 1: Check for empty queue before peeking
Accessing q[0] when empty returns undefined but may be unclear; better to check length.
Step 2: Use conditional to safely peek front
Using q.length > 0 ? q[0] : 'Queue is empty' returns front if exists, else message.
Final Answer:
console.log(q.length > 0 ? q[0] : 'Queue is empty'); -> Option C
Quick Check:
Safe peek uses length check before access [OK]
Hint: Check length before peek to avoid errors [OK]
Common Mistakes:
Peeking without checking empty queue
Using pop() or shift() which remove elements
Assuming q[0] always exists
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.