Arrays
Programming Languages · JavaScript Functions & Arrays · 12 min
Keep lists of values in arrays: read them, add to them, search them and slice them.
Making a list
An array is a list of values in square brackets, separated by commas. .length tells you how many items it has.
const snacks = ["chips", "nuts"];
console.log(snacks.length); // 2
Create a
constarraycolorswith"red","green"and"blue".Print
colors.length.
Getting items by position
Each item has a position number called an index. Counting starts at 0, so the first item is [0].
const pets = ["cat", "dog", "fish"];
console.log(pets[0]); // cat
console.log(pets[2]); // fish
You can also replace an item: pets[1] = "hamster";
Print the first color.
Change the second color to
"yellow", then print it.
push and pop
.push(x) adds x to the end of an array. .pop() removes the last item and gives it back to you.
const stack = ["a", "b"];
stack.push("c"); // ["a", "b", "c"]
const top = stack.pop(); // top is "c"
Yes, you can change a const array's contents. const only stops you replacing the whole array.
Push
"Cara"ontoqueue, then printqueue.length.Pop the last item into a variable
lastand print it.
Searching: includes and indexOf
.includes(x) answers true or false: is x in the array? .indexOf(x) tells you where it is, or -1 if it isn't there at all.
const nums = [4, 8, 15];
console.log(nums.includes(8)); // true
console.log(nums.indexOf(15)); // 2
Print whether
menuincludes"pasta".Print the index of
"salad".Print the index of
"cake"(it's not on the menu).
Copying part of a list: slice
.slice(start, end) copies a piece of an array into a new array. It includes start but stops just before end. The original stays the same.
const letters = ["a", "b", "c", "d"];
console.log(letters.slice(1, 3)); // ["b","c"]
Create
midweekwithdays.slice(1, 4)and print it.Print
days.lengthto check the original still has all 5 days.
Put it together: a playlist
One handy trick: the last item is always at index length - 1, however long the list gets.
list[list.length - 1]
Now grow a playlist and look at it.
Push
"Night Drive"and then"Outro"ontoplaylist.Print
Songs:and the number of songs, usingplaylist.length.Print the last song with
playlist[playlist.length - 1].