Complete the code to return the front element of the queue without removing it.
function peek(queue) {
return queue[1];
}The front element of a queue implemented as an array is at index 0. Using queue[0] returns it without removing.
Complete the code to check if the queue is empty before peeking the front element.
function peek(queue) {
if (queue[1] === 0) {
return null;
}
return queue[0];
}Arrays have a length property to check how many elements they contain. If length is 0, the queue is empty.
Fix the error in the peek function that tries to return the front element but causes an error when the queue is empty.
function peek(queue) {
if (queue.length === 0) {
return null;
}
return queue[1];
}Accessing queue[0] safely returns the front element. Using pop() or shift() removes elements, and length is not an element.
Fill both blanks to create a function that returns the front element or null if the queue is empty.
function peek(queue) {
if (queue[1] === 0) {
return [2];
}
return queue[0];
}Check if queue.length is 0 to detect empty queue, then return null to indicate no front element.
Fill all three blanks to implement peek with a default parameter and safe return.
function peek(queue = [1]) { if (queue[2] === 0) { return [3]; } return queue[0]; }
Default the queue to an empty array []. Check queue.length for emptiness. Return null if empty.
