DEV Community

Codecupdev
Codecupdev

Posted on • Updated on

A Tour Through JavaScript Arrays With Ten Methods Beginners Should Know

Image description

A video which introduces arrays in this article can be found here.

What is a data structure?

In computer science we use the term data structure to describe ways that we can store our data and organise our data. Arrays are a data structure in Javascript. Arrays can be stored within a variable and inside of the array we can store any of the primitive values, arrays can also store other arrays. The special thing about an array is that it is an ordered list.
If we have data that we need to preserve the order of then we would want to use an array. The days of the week might be a good example but another could be social media posts which are shown in order of date.

Introducing arrays

We use two square brackets to create an array []. If you are familiar with strings, similarly with arrays each item in the array is called an element. Each of these elements has a numbered position called an index. The indices start counting from zero so as with strings we can say that arrays are zero-indexed.

Image description

The example above shows an example of an array literal containing numbers stored in a variable countToFive. We could easily create an array of mixed data types which would look like the following:

let countToFive = [1, null, “hi”, false];

Enter fullscreen mode Exit fullscreen mode

Array indices

As I previously mentioned elements in an array have an index just like when you are working with strings. The indices start from zero and you can access the array elements in the exact same way by using square brackets. If we wanted to access the first element of the countToFive array we would do the following:

let countToFive = [1, null, “hi”, false];
countToFive[0]
// ---> Returns 1
Enter fullscreen mode Exit fullscreen mode

Length

We can get the length of the array by using the name of the array and the length property. For the countToFive array we would do the following:

let countToFive = [1, null, “hi”, false];
countToFive.length
// ---> Returns 4
Enter fullscreen mode Exit fullscreen mode

Mutability

Unlike strings which are immutable meaning that they cannot be changed, arrays are mutable which means we can change them. This means if we want to change an array element we can access and update it directly. So in the new version of the countToFive array, if we wanted to change the last element (false) to be true we would do the following:


let countToFive = [1, null, “hi”, false];
countToFive[3] = true
console.log(countToFive);

// ---> Returns [1, null, 'hi', true]
Enter fullscreen mode Exit fullscreen mode

If you are familiar with the primitive data types in JavaScript such as numbers, booleans, strings, null and undefined, you will likely know that when you store one of these data types in a variable they are stored by value so it’s the value itself which is stored.

Reference types

Arrays (and objects) are much larger and can use much more memory so these are what we call reference types. When you use reference types it is a reference to the data is that is stored in memory. It’s a bit like saying you have an address for where you live. It is an address to the data that’s stored in the computers memory as opposed to the data itself being stored. Due to this fact we can change the data stored inside the array itself which is why we say that arrays are mutable, we can create an array using const and then change the data inside of the array. Below is a repeat of the above example which previously used let but this time we use const and you can see that it still works.


const countToFive = [1, null, “hi”, false];
countToFive[3] = true;
console.log(countToFive);

// ---> Returns [1, null, 'hi', true]
Enter fullscreen mode Exit fullscreen mode

This also means that when we use an array method the method will directly impact the array as opposed to when you work with strings where you have to manually save the changes.
The only thing you can’t do when the array is created with const is change the entire array. If you wanted to do this then you could have to create the array with let.


const sizes = [9, 12, 13];
sizes = [1, 2, 3];
// ---> Returns Uncaught TypeError: Assignment to constant variable.
    at <anonymous>:1:7
Enter fullscreen mode Exit fullscreen mode

If we repeat this again but this time using let you can see that because the array was created with let and not const we are this time able to do this.

let sizes = [9, 12, 13];
sizes = [1, 2, 3];
// ---> [1, 2, 3];
Enter fullscreen mode Exit fullscreen mode

Methods

JavaScript also has some built in methods which make working with arrays easier, Now we will have a look at some of these.

IndexOf

The indexOf method parameters take the value we are looking for and return the zero-based index of that value. If the value exists multiple times within the array the method will only return the index of the first instance of the element. If the value does not exist the method will return -1. We can pass an optional second argument which is the index to look from.

Image description

In the above example we start by storing an array of numbers in a variable called countdown. Next we call the indexOf method passing in 4. The element in the coundown array at the index of 4 is 1 and this is what we get as the return value.
We try this again but this time passing in the index of 10. There is no element at this index so we get -1 as the return value.
We repeat this once more passing in 4 as the value we are looking for and 3 as the index to look from. As we are looking from the index of 3 and element 4 only exists at the index of 1 we get -1 as the return value.

Pop

To remove an element from the end of an array JavaScript provides us with a method called pop.
The pop method does not take any arguments. It will remove the last element from the end of an array and the return value is the value removed by the method.

Image description

In the above example, we will create an array called drinks and inside of this array, we add the elements tea, coffee, sprite and Ribena. We want to remove Ribena from the drinks array so we use the method pop. Ribena is the return value of the method. When we console.log the drinks array it now only has three elements and Ribena has been removed.

Push

The push method allows us to add items to the end of an array. The method can take one or more arguments separated by commas. The values from the parameters (inside the ()) are then appended (added) on to the end of the array. The return value will be the number of elements in the array after the new items have been pushed on.

Image description

In the above example, we create an array called months and inside of this array we add the elements jan, feb and march. We want to add an additional element, april so we use the method push.
The return value is 4 because the array now contains 4 elements. When we console.log the months array it now includes april inside of the array.

Shift

The shift method will remove the first element from an array. The method is very similar to the pop method but it removes the first element instead of the last element. The return value is the value that was removed from the array.

Image description

In the above example, we create an array of some music genres stored in a variable called music. We call the shift method on the array which removes the first element of the array and returns it. Now when we recall the music array it only contains two elements and the string “classical” has been removed.

Unshift

To add items to the start of an array we can use the unshift method. The method is very similar to the push method except the items are added to the start of the array. The return value of the method is the number of elements within the array after the method has run.

Image description

In the above example, we create a clothes array with some strings representing items of clothing. Next, we call the unshift method and pass in the string “socks”. The return value of the unshift method is the number of elements after the method has run so we get 5. When we recall the clothes array we get the updated array with “socks” as the first element.

Includes

The includes method allows us to see if an array includes a specific element. The return value of the method will always be a boolean (true or false). The method optionally allows you pass in, as a parameter, the index of where you would like to look from. If you do not pass an index to the parameters then the entire array will be checked.

Image description

In the above example, we start by creating a variable called cities and store an array that contains strings of city names. Next, we call the includes method on the cities array to check whether the array includes Bangkok . As the cities array does include Bangkok we get true as the return value.
We repeat this again but this time we look for Mumbai. The cities array does not include this string so we get false as the return value.

Reverse

To reverse the elements within an array we can use the reverse method. The method does not take anything inside its parameters. The return value will be the array with all the elements in reverse order.

In the above example we create a variable called shoes which stores an array of strings. We then call the reverse method, We get the array returned to us but in reverse order.

Image description

Join

At times we may wish to turn the elements of an array into a string. The join method enables us to do this. The return value of the method is a string with all the joined array elements. We have the option to pass a parameter into the method and this will act as a separator for the elements. For example, join(“-”) would return the elements separated by hyphens whereas join(“ “) would separate the elements with a space.

Image description

In the example, we create a variable called laugh which stores an array of some strings. We then call the join method with an empty string. This joins together all the strings which are not separated. Later we repeat this but this time we add some whitespace as the separator. We get the strings returned to us but with whitespace between each element.

Splice

The splice method adds or removes elements to or from an array.

  • The first parameter of the method is the index at which the method should start changing the array.

  • The second parameter is optional and is the number of elements that should be removed.

  • The third parameter is also optional and is the elements you would like to add to the array.

The method returns an array with the elements which have been removed. If no elements are removed then an empty array is returned.

Image description

In the example, we create a pets variable that stores an array of strings. We start by calling the splice method. The return value of this would be an empty array as we are not removing any elements. We said, at the index of 1, remove no elements but add the string rabbit. When we console.log out the pets array we can see that the rabbit element has been added at the index position of one.
Next, we use the splice method again but this time with the arguments 0 and 4. By doing this we are saying, starting at the index of 0 remove 4 elements. As we are removing elements this time the method returns an array with the four elements which have been removed. When we console.log out the pets element this time it only contains goldfish.

Slice

The slice method lets us copy part of an existing array. The method can take two parameters.

  • If only one value is passed into the parameters the array returned will start at that element through to the end of the array.

  • If two values are passed into the parameters then the returned array will start from the first value and continue up to but not including the index of the second value.

  • If you pass in a negative value to the parameters then the method will count backward that amount of indices.

  • If you do not pass any parameters into the method then the entire array will be returned.

Image description

In the above example, we start by creating an array of strings which we store in a variable called subjects. We call the slice method on the subjects array passing in a single value of 1. The method returns all the elements from the index of 1 up until the end of the array because we did not pass in a stopping point for the second parameter.
If we had included a second parameter we would get the following output:

const subjects = ["maths", "english", "art", "history"];
subjects.slice(1, 2);
// Returns ---> ["english"]
Enter fullscreen mode Exit fullscreen mode

Conclusion

Please feel free to post any comments, questions or feedback!

I also have a Skillshare course on the above topic which can be found here Using this link you can get one months free access.

Top comments (0)