Working with JavaScript Arrays Pt. 1

Photo by Max Chen on Unsplash

Working with JavaScript Arrays Pt. 1

Knowing about Arrays are one of the most important skills you can have in a programming language, especially for one learning JavaScript.

We'll look at how with arrays, we can retrieve, add, and remove items stored in an array.

Arrays are used to store a list of data items under a single variable name. Usually described as list-like objects, they are objects that contain multiple values stored in a list. Array objects are stored in variables and then be used in the same way as any other type of value. However, we can access each value inside the list individually.

Arrays can be useful in such examples as if you had a dresser, and each drawer had different clothing items, and you wanted to access which drawer had what certain items. Another example would be if you wanted to find the many different prices of items, and wanted to send an invoice while adding up the prices together and print out the total together.

Creating Arrays

Suppose we wanted to store an array that had items that made up a skateboard: image.png

Which would show you each of the items inside of the variable of skateboard.

Not only can we store strings, such as what we did above, but we can also store other data types such as numbers, objects, and even other arrays. We can even mix other data types in a single array. Such an example: image.png

Finding the Arrays Length

By using the length property, we can find the length of the array. If wanted to find the length of the array called food, it would look something like this: image.png As you see, there are 5 items inside the array of food, so 5 would be logged to the console.

Accessing Array Items

You would think by looking at an array, that the items index would start with 1, but in fact, all arrays start with the item index of 0, with the second item being 1, and so on. Using bracket notation we can access the item index of a particular item in the array. image.png

Say if we wanted to change the item inside of the array pop, we can do something like this. image.png Here we change the first item, which is at the index of 0, to rock n rye.

In the next post, I'll talk about how to find items in an array, adding items, removing items, and accessing every item.