There is a queue at a stall: Ani, Budi, Citra. If someone asks what number Ani is, you say 1. JavaScript says 0. This difference of one is the most common cause of mistakes with arrays.
An array is a single variable that holds an ordered list of values, like a list of friends' names or a list of prices. The queue at the stall can be stored as an array: each person becomes one item of the array, in queue order. Each item has a position number called its index. With an array, you don't need to make the variables name1, name2, name3 one by one.
Reading items by index
This example makes an array of three fruit names, then reads its items:
const fruits = ["apple", "mango", "orange"];
console.log(fruits[0]); // apple
console.log(fruits[1]); // mango
console.log(fruits[2]); // orange
console.log(fruits[5]); // undefined
console.log(fruits.length); // 3
[ ]makes an array. Its items are separated by commas.fruits[0]reads the item at index 0, which is the first item. Indexes count from 0 because an index is the distance from the start of the array. The first item is 0 away from the start, so its index is 0. The second item is at index 1.- This array has only three items, so
fruits[5]is empty. It givesundefined, not an error. fruits.lengthis the number of items in the array.lengthis written without parentheses, becauselengthis a property (a fact about the array), not a method (a command).
The last item is always at index length - 1, so fruits[fruits.length - 1] is "orange". The first item is always arr[0], not arr[1] (arr here stands for any array).
Adding and removing at the end: push and pop
push and pop work at the end of an array:
const numbers = [10, 20];
const newLength = numbers.push(30);
console.log(numbers); // [10, 20, 30]
console.log(newLength); // 3
const removed = numbers.pop();
console.log(removed); // 30
console.log(numbers); // [10, 20]
push(x)addsxto the end of the array, and the original array changes too. Whatpushreturns is the new number of items, not the array.pop()removes the last item and returns the item it removed.
The contents of an array stored in a const can still change. const only stops the variable from being given a different array.
Adding and removing at the front: unshift and shift
unshift and shift work like push and pop, but at the front of an array:
const queue = ["Budi", "Citra"];
queue.unshift("Ani");
console.log(queue); // ["Ani", "Budi", "Citra"]
console.log(queue.length); // 3
const first = queue.shift();
console.log(first); // Ani
console.log(queue); // ["Budi", "Citra"]
unshift(x)addsxat the front. Every other item moves back one index:"Budi", which was at index 0, is now at index 1.shift()removes the first item and returns the item it removed.
Checking for an item: includes
includes checks whether a value is in an array:
const names = ["Ani", "Budi"];
console.log(names.includes("Budi")); // true
console.log(names.includes("Dodi")); // false
console.log(names.includes("budi")); // false
includes(x) gives true if x is in the array, and false if it isn't. Capital and small letters must match exactly. That is why "budi" with a lowercase b isn't found: the array holds "Budi".
Replacing and removing items in the middle. push and pop only work at the end of an array. A to-do list needs more than that:
const tasks = ["wash dishes", "buy sugar", "sweep floor"];
tasks[1] = "buy rice";
const position = tasks.indexOf("wash dishes");
console.log(position); // 0
tasks.splice(position, 1);
console.log(tasks); // ["buy rice", "sweep floor"]
console.log(tasks.at(-1)); // sweep floor
tasks[1] = "buy rice"replaces the item at index 1,"buy sugar".indexOf(x)gives the index of the first item equal tox, or-1if there is none.splice(i, n)removesnitems starting at indexi, and it changes the original array.at(-1)reads the last item. A negative index counts from the end.
Check position !== -1 before splice. If the item is not there, position holds -1, and splice(-1, 1) removes the last item instead.
⚠️ Brackets on length, an index too far, and a copy that isn't one
length()with parentheses.fruits.length()throws a TypeError, becauselengthis not a function you can call. Just writefruits.length.- The last item at
arr[arr.length]. That index is always empty, because indexes start at 0. The last item is atarr[arr.length - 1]. - Copying an array with
=.const b = a;doesn't make a copy. That line only gives the same array a second name, sob.push(...)changesatoo. Make a copy with[...a]. This copy is shallow: if the array holds arrays or objects, both copies still share those inner ones (see the Spread & Rest lesson).
TL;DR: An array is an ordered list of values in one variable, written ["a", "b", "c"]. Each item has a position number called its index. Indexes start at 0, so the first item is arr[0] and the second is arr[1]. arr.length is the number of items, written without parentheses, and the last item is at arr[arr.length - 1]. push adds one item to the end and returns the new number of items, pop removes the last item. unshift adds and shift removes, but at the front of the array. includes(x) gives true if x is in the array, and false if it isn't.
⚡ Indexes start at 0
Write:
const fruits = ["apple", "mango", "orange"];
console.log(fruits[0]); // apple
console.log(fruits.length); // 3
Guess first: what does fruits[3] hold?
undefined, not an error. The three items of this array are at indexes 0, 1 and 2. The last item is at index length - 1, which is fruits[2].
Meaning: An array is an ordered list of values, and an index is the position number of each item. An index counts the distance from the start of the array, so the first item is at fruits[0]. fruits.length is the number of items in the array, written without parentheses.
⚡ push and pop at the end
Write:
const numbers = [10, 20];
const newLength = numbers.push(30);
console.log(newLength); // ?
Guess first: what does newLength hold?
3. push returns the new number of items, not the array. The array numbers itself now holds [10, 20, 30].
Meaning: push(x) adds x to the end of the array and changes the original array. pop() removes the last item and returns the item it removed. At the front of the array, the matching pair is unshift(x) to add and shift() to remove.
⚡ Check with includes
Write:
const names = ["Ani", "Budi"];
names.includes("Budi"); // true
names.includes("budi"); // false
Meaning: includes(x) gives true if x is in the array, and false if it isn't. The letters must match exactly, uppercase and lowercase included. That is why "budi" isn't found.