Home › Learn › JavaScript › Arrays

Arrays

Lesson 16 of 40. Ordered lists you can grow, shrink, and index.

An array holds values in order: const queue = ["Ann", "Ben"];. Positions start at zero, queue[0] is the first item, queue[queue.length - 1] the last (or queue.at(-1)), and .length is the count. Arrays declared with const can still be changed; const only stops reassigning the variable.

.push(x) adds to the end and .pop() removes from the end; .unshift(x) and .shift() do the same at the front. .indexOf(x) finds a position (-1 if absent), .includes(x) asks yes or no, and .splice(i, 1) removes one item at position i.

const stack = [1, 2];
stack.push(3);        // [1, 2, 3]
stack.unshift(0);     // [0, 1, 2, 3]
stack.splice(2, 1);   // [0, 1, 3]
const last = stack.pop();   // 3

Your task

Starting from queue in the starter, push "Cai", put "Zed" at the front, and remove "Ben" (find its position, then splice). Then set first to the first item, last to the last, and size to the length.

Hint 1

queue.unshift("Zed") puts it at the front.

Hint 2

queue.splice(queue.indexOf("Ben"), 1) removes Ben.

Show the solution
const queue = ["Ann", "Ben"];

queue.push("Cai");
queue.unshift("Zed");
queue.splice(queue.indexOf("Ben"), 1);

const first = queue[0];
const last = queue[queue.length - 1];
const size = queue.length;

    Runs in an isolated web worker in this tab; nothing is sent anywhere.