Let’s create a list called groceries. Let’s do this in the Chrome devTools console tab. How to open the console was covered in this post here. To make our grocery list we need to declare a new variable. Just like when we declared our string variable in the previous post, we will use the var keyword. However, to create the list we need to use a pair of square brackets . We can make an empty list like this:
var groceries = , but this isn’t very useful. In order to have things in our list, we add them inside our brackets and separate them with a comma. Strings still need to be in quotes, so a list with milk and bread would look like:
var. Go ahead and give that a try, type that in and press enter. Now to see your list again, you can type
groceries = ["milk", "bread"]
groceries and hit enter.
Array of Numbers
Arrays can also hold numbers. Creating an array with a number is the same as with a string except you don’t place numbers in quotes. For example,
= [4, 8, 15, 16, 23, 42]
Other useful array features
Arrays have some cool features that make them very useful. An array can tell you how many items it has with the length property. To check the length of our groceries list, we would use
var (Looks like the parents of these students were not very creative in naming their children), we could enter students.indexOf(“John”) to find that John’s index is 1. Well, that may not have been what you expected, since Mary is the first student, but our indexes start with 0. So Mary’s index would be 0 and John’s would be 1.
students = ["Mary", "John", "Steve",
f the item is not found, findIndex returns -1. It’s a common operation to use this in order to check if an item is in an array. The logic looks like this: “if findIndex of needle in haystack is -1 then the needle is not present”.
Arrays come with a lot of other properties and built-in functions. Check out this list on MDN to see what else an array can do. I’ll cover arrays in more detail in a later post.
Feel free to use the comment section to create some array examples.