An array is a type of list. It can hold a bunch of items in it. And those items can be any type of variable, object, function, or even other arrays. Arrays are immensely useful, as are the many methods that are predefined for them.
Use the let keyword and square brackets []
to declare an array.
In JavaScript, arrays are always considered true, even if they they are empty, []
.
To use an array, you often need to use an index. This represents the location of an item inside an array. Use square brackets to access items by index.
Indexes start at zero. So the first item is index 0
, not index 1
.
let colors = ["blue", "red", "green"];
Element in the colors array | "blue" | "red" | "green" | //empty |
Index number | 0 | 1 | 2 | 3 |
How to access the element | color[0] |
color[1] |
color[2] |
color[3] |
Output | "blue" | "red" | "green" | undefined |
There was no item in the numbers
list as the fifth index, so it comes back as undefined.
That's better than it returning an error, but it pays to be careful not to overshoot your array's size.
You can also change an array item by reassigning the value at a given index. Let's say that test2
tripped up a lots of kids and you decide to give a new test. You can replace the test2
score with the
newTest2
score by using the following: scores[1] = newTest2;
Just set the array index you want to change to the new value!
.length
.forEach()
. We'll get to that in a bit.
When you need to know how many elements are in your array, all you need to do is use the .length
property. This returns the number of items in your array up to the last item
that is defined. This means that if you have any gaps in your array (undefined spots)
those are counted as well. This is just like the .length
property of
strings.
The testArray
example goes like this: We created an empty array []
, then we set a value
at index 4
. Remember that the array starts at index 0
, so index 4
is actually
the fifth item. Indexes 0
, 1
, 2
, and 3
were never given values,
so they're all undefined. But in counting the length of the array, the computer counts
all the way up to that fifth spot, which is holding "testing"
inside. So it returns a length of
5
.
.indexOf(item)
This is similar to the .indexOf()
method for strings. You attach this
method to an array and pass it something you're looking for. If it finds the item, it returns its index position. If
it can't find it, then it returns -1
.
This process is called concatenation, like you can do with strings. This creates a new array with the lists joined together, and the original lists remain untouched.
Let's say two friends went Trick-or-Treating for Halloween. They decide to pour all their treats into a single pile. It would go something like this,