Creating and Accessing Arrays
An array is an ordered list of values, numbered from zero, and it is how JavaScript holds any collection of things.
Square brackets make an array and read a position. length gives the count, so the last index is length minus one. push, pop, shift and unshift add and remove at the ends, and all four change the array in place.
EXERCISE
1An Ordered List of Anything
An array holds several values in a known order under a single name, which is what makes looping possible.
An object answers "what do I know about this one thing?". An array answers "how many of these do I have, and in what order?".
Making one:
const names = ["Ada", "Grace", "Alan"];
const scores = [90, 72, 85];
const mixed = ["text", 42, true, null];
const empty = [];
console.log(names.length); // 3
console.log(empty.length); // 0
console.log(typeof names); // "object" arrays ARE objects
console.log(Array.isArray(names)); // true
Reading by position, counting from zero:
const names = ["Ada", "Grace", "Alan"];
console.log(names[0]); // Ada
console.log(names[1]); // Grace
console.log(names[2]); // Alan
console.log(names[3]); // undefined <- past the end, no error
console.log(names[names.length - 1]); // Alan the last one
console.log(names.at(-1)); // Alan the clearer way
Writing by position:
const names = ["Ada", "Grace", "Alan"];
names[1] = "Grace Hopper";
console.log(names); // [ 'Ada', 'Grace Hopper', 'Alan' ]
names[5] = "Katherine";
console.log(names); // [ 'Ada', 'Grace Hopper', 'Alan', <2 empty items>, 'Katherine' ]
console.log(names.length); // 6 <- gaps are real and awkward
Arrays of objects, which is what real data looks like:
const users = [
{ id: 1, name: "Ada", active: true },
{ id: 2, name: "Grace", active: false },
];
console.log(users[0].name); // Ada
console.log(users[1].active); // false
console.log(users.length); // 2
An array of objects is the shape almost all real data arrives in: a result, an response, a list of rows. Everything in the rest of this unit exists to work with that shape, so getting comfortable reading users[0].name now makes the seven lessons that follow much easier.
EXERCISE
2Adding and Removing at the Ends
Four methods change an array's contents in place, two at the end and two at the start.
push and pop work at the end:
const stack = ["a", "b"];
stack.push("c");
console.log(stack); // [ 'a', 'b', 'c' ]
console.log(stack.length); // 3
const last = stack.pop();
console.log(last); // c <- pop returns what it removed
console.log(stack); // [ 'a', 'b' ]
unshift and shift work at the start:
const queue = ["b", "c"];
queue.unshift("a");
console.log(queue); // [ 'a', 'b', 'c' ]
const first = queue.shift();
console.log(first); // a
console.log(queue); // [ 'b', 'c' ]
All four change the original array:
const items = [1, 2, 3];
items.push(4);
console.log(items); // [ 1, 2, 3, 4 ] <- the const array was changed
// const stops you REPLACING the array:
// items = [9]; TypeError: Assignment to constant variable.
// It does not stop you changing what is inside it.
push returns the new length, which catches people out:
const items = [1, 2];
const result = items.push(3);
console.log(result); // 3 <- the new LENGTH, not the array
console.log(items); // [ 1, 2, 3 ]
// So this does not do what it looks like:
// const bigger = items.push(4); bigger is 4, a number
Adding several at once:
const items = [1];
items.push(2, 3, 4);
console.log(items); // [ 1, 2, 3, 4 ]
push and pop are far faster than shift and unshift on a long array, because adding at the start means renumbering every other item. It rarely matters for a list of ten, and it matters a great deal for a list of a hundred thousand. When either end would do, use the end.
EXERCISE
3Looping Over an Array
Three loops walk an array, and choosing between them is mostly about whether you need the position.
for-of, when you want each item:
const names = ["Ada", "Grace", "Alan"];
for (const name of names) {
console.log(name);
}
// Ada
// Grace
// Alan
A counted for, when you need the index:
for (let i = 0; i < names.length; i++) {
console.log(`${i + 1}. ${names[i]}`);
}
// 1. Ada
// 2. Grace
// 3. Alan
entries, when you want both and prefer for-of:
for (const [i, name] of names.entries()) {
console.log(`${i}: ${name}`);
}
// 0: Ada
// 1: Grace
// 2: Alan
Building a result as you go:
const scores = [90, 72, 85];
let total = 0;
for (const score of scores) {
total += score;
}
console.log(total); // 247
console.log(total / scores.length); // 82.33333333333333
And the one to avoid on arrays:
const names = ["Ada", "Grace"];
for (const key in names) {
console.log(key, typeof key);
}
// 0 string
// 1 string
// for-in gives you KEYS, as strings, and is meant for objects.
// On arrays it is a source of bugs. Use for-of or a counted for.
Pro Tip:
for-ofgives you values andfor-ingives you keys, and the one-letter difference between them causes real confusion. On an array you nearly always want values, sofor-ofis the default. Unit 8 covers the case wherefor-inis the right tool, which is walking an object's properties.
