Doug Winnie shows how to create a collection of values using an array. Then Doug shows how to work with individual values in the array after it is created using bracket notation and the element index number.
Then separate each value with a comma. Close the array with a closed square bracket. This array has four elements and each element has an index number that you use to access each element. The first is element zero. So the string Doug is element zero, in the array named myarray. You can also create an array with a mixture of variable types. You create it the same way and separate each value with comma. I can create a variable called myMixedArray, and using the square brackets, put in the values.
There are multiple ways you can access an array. You can access the entire collection of values as a single set, or you can pinpoint specific items inside of it. If we create a console message and we pass on the entire array, we can see what shows up. Console.log and we'll pass in the entire array. Save and load the page in the browser. You'll see in the console that there is an array and it has four elements.
Open the disclosure triangle to expand the array. Inside are all the individual elements and the index numbers for each value in the array. At the bottom it also shows the array length, which is the property in every array. Create another console message for the other array in our code, and save and reload. You'll see the array again. This time with three elements. Each of a different type. To access a single element you'll use the array name and then use a pair of square brackets directly after the array name with no spaces.
Then inside, enter in the element index number you want to access. This can be a literal number or a variable, which is how you will want to work with Arrays in a loop. We can access the first element using the number zero. Let's output the first element to the console. Console.log and we'll access myarray, but we're going to pinpoint element zero. So we use the open and closed square brackets and put the index element number inside. Save and reload the browser.
As you can see, we get the string Doug, which is the first position in the array. If we try to access an element that doesn't exist, we'll get an error that the element is undefined. Create a new console message and this time we'll access element index four, which would be the fifth element in the array, which doesn't exist. Save and reload the browser. You'll see that you get an error of undefined. That is because element index four is undefined in the array and can't be found.
- Setting up your development environment
- Working with values and variables
- Using and customizing functions
- Creating conditional tests
- Using loops
- Creating and changing arrays