Array operations
🏠The everyday picture
A queue at a ticket counter: people join at the back, leave from the front, someone checks if a friend is in the queue, someone counts heads. Arrays have a built-in tool for each of these.
📘What it really is
Adding and removing:
push(item)adds to the end;pop()removes from the end;unshift(item)adds to the start;shift()removes from the start.
Finding:
includes(item): is it there? (trueorfalse);indexOf(item): where is it? (-1if not found);find(test): the first item that passes a test (orundefined);some(test)andevery(test): does any, or every, item pass?
Copying and joining:
slice(start, end)copies part of an array without changing it;[...a, ...b](the spread syntax) makes a new array from two others;join(", ")turns an array into one piece of text.
Changing in place (careful):
splice(index, count)removes items from the middle and changes the original;sort()andreverse()also change the original.
Some methods change the array; others return a new one and leave the original alone. Mixing them up is a classic source of bugs. Prefer the ones that return something new.
🖱️Try it
In catalogue.js:
const cart = ["Pen", "Notebook"];
cart.push("Bag");
console.log(cart.includes("Pen"));
console.log(cart.indexOf("Bag"));
const firstTwo = cart.slice(0, 2);
console.log(firstTwo, cart);
console.log(cart.join(", "));
Predict each output before you run it.
✅Quick check
indexOf returns -1. What does that mean?
Show the answer
The item isn't in the array.
Which changes the original array: slice or splice?
Show the answer
splice. slice returns a copy and leaves the original alone.
