A queue changes over time
A collection queue contains references A and B. C joins at the end; A is served from the front. Predict the final queue before execution.
const queue = ["A", "B"];
queue.push("C");
const served = queue.shift();
console.assert(served === "A");
console.assert(queue.length === 2);
console.assert(queue[0] === "B");
push adds at the end; pop removes from the end. unshift adds at the start; shift removes from the start. The removal methods return the removed entry, or undefined when the array is empty. These methods mutate the existing array.
Const prevents assigning a different array to queue; it does not freeze the array's contents.
Two names can refer to the same collection
const original = [10, 20];
const alias = original;
alias.push(30);
console.assert(original.length === 3);
const copy = [...original];
copy.pop();
console.assert(original.length === 3);
console.assert(copy.length === 2);
Assignment does not clone the array. The spread syntax ... inside brackets copies its entries into a new array. This is a shallow copy: if entries are objects, their references are still shared. We will inspect that distinction in the objects module.
Independent exercise
A preview should add D to a queue without changing the actual queue. Begin with A and B. Implement the preview, then verify both lengths and the first entry of each.
Correction
Create preview = [...queue], then push D onto preview. The original length remains 2; preview length is 3; both start with A. Simply assigning preview = queue would share the same array and change the real queue.
Review
Before calling a mutating method, ask who else may hold this array. Mutation is useful when intentional; unexpected shared mutation is the problem. For a queue, also confirm whether serving should remove an entry or preserve it in a history record.