Byte's sock empire
Arrays, length, indexes, push, for and while loops, break/continue, includes and indexOf.
const socks = ["striped", "polka dot", "holey"];
console.log(socks.length);
console.log(socks[0]);
console.log(socks[2]);The essentials of arrays:
- elements go in square brackets, separated by commas;
arr.lengthis how many elements there are;arr[i]is the element at number (index)i, counting from zero;- the last element is
arr[arr.length - 1].
To add an element at the end, use push. An array declared with const can still be changed: const only stops you from replacing it entirely.
const socks = ["left"];
socks.push("right");
console.log(socks);
console.log(socks.length);Now a loop — a way to go through every element without copying code. for...of puts each element into a variable in turn.
const socks = ["striped", "polka dot", "holey"];
for (const sock of socks) {
console.log("Sniffing sock: " + sock);
}A classic pattern is the accumulator: create a variable before the loop and build up the result in it.
const prices = [100, 250, 50];
let total = 0;
for (const price of prices) {
total += price;
}
console.log(total);If you need the element's number, there's the classic for with a counter: start at 0, keep going while i < length, and add 1 each time.
const socks = ["red", "blue"];
for (let i = 0; i < socks.length; i++) {
console.log(i + ": " + socks[i]);
}Sometimes you don't know in advance how many steps there will be. I take socks off the radiator while there's room in my backpack — and I have no idea how many are hanging there. That's what while is for: “repeat as long as the condition is true”. The condition is checked before every step.
const capacity = 3;
let backpack = 0;
while (backpack < capacity) {
backpack++;
console.log("Grabbed sock #" + backpack);
}
console.log("Backpack full!");for is for when you know how many steps. while is for when you know until when.Two words let you steer any loop from the inside:
break— leave the loop right now, don't look at the remaining elements;- continue — drop the current step and move on to the next one.
const socks = ["intact", "holey", "intact", "golden", "intact"];
for (const sock of socks) {
if (sock === "holey") {
continue; // skip the holey one — on to the next
}
if (sock === "golden") {
console.log("A golden sock! I need nothing else.");
break;
}
console.log("Taking: " + sock);
}break ended the loop early.And to simply find out whether a sock is in the collection, you don't need a loop at all — arrays can search by themselves:
arr.includes(x)—trueorfalse;arr.indexOf(x)— the index of the first match, or-1if there's none.
const socks = ["red", "blue", "red"];
console.log(socks.includes("blue"));
console.log(socks.indexOf("red"));
console.log(socks.indexOf("green"));indexOf finds only the first red sock.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.