Arrays are a data type that contain many different values inside of them. These are useful when we have a list of information we need to work with.
For example, let’s say we want to run console.log
on all the companies we applied to. We could do something like this
var company1 = "Company A";
var company2 = "Company B";
var company3 = "Company C";
console.log(company1);
console.log(company2);
console.log(company3);
This is a lot of repeated code and extra variables. Every time we add a new value we have to add a new variable.
We could fix this by creating one value that contains many values.
var companies = ["Company A", "Company B", "Company C"];
With our array, we get a specific value in our array using an index value.
Index values for arrays start at 0, not at 1
Since we have three values in our array, we can numbers 0 – 2 at our disposal.
var companies = ["Company A", "Company B", "Company C"];
console.log(companies[0]);
console.log(companies[1]);
console.log(companies[2]);
It’s also important we learn about the .length
attribute in an array.
The length attribute of an array tells us how many items are in our array.
So for our array, calling we would have a length of 3.
We can print out the length of our array in the console like this:
var companies = ["Company A", "Company B", "Company C"];
console.log(companies.length);
Next we’d want to iterate through this array. Iterating through an array requires looping through it.
var companies = ["Company A", "Company B", "Company C"];
for(var i = 0; i <= companies.length; i++) {
console.log(companies[i]);
}
Now our code only takes up 4 line, instead of the 7 we started with.
We can also add a new element to our companies array without worrying about adding another console.log
var companies = ["Company A", "Company B", "Company C", "Company D"];
for(var i = 0; i <= companies.length; i++) {
console.log(companies[i]);
}