While coding in JavaScript, we often have to store related values together. But, a simple variable is not capable of doing that. So, the concept of an array is introduced in JavaScript that reserves consecutive memory locations. Meaning that we can now arrange our related data under a single name.
Today, you will learn about JavaScript arrays and some built-in functions that are specifically designed to work with arrays. At first, I will focus on the basics of creating or updating an array. But, later on, I’ll introduce you with commonly used JavaScript array methods.
The array is like a list of values from which a specific element can be accessed using the array name and its index. Whereas an index is nothing but a number that informs us about the position of an element inside an array.
Unlike many other programming languages, JavaScript only supports numeric indexes. But, there are some ways to depict an associative array in JavaScript (e.g. using objects).
The basic reason for using an array is that a simple variable can not store multiple values. For example, we can’t do something like this:
var numbers = 12, 26, 34, 49, 50;
Note:- JavaScript automatically assigns a numeric index to each element of an array. Remember that the first element of an array always starts with 0 index.
In this section, you will learn about working with arrays in JavaScript. Basically, we will be creating an array, display it, then modify, and finally delete it.
Creating an array in JavaScript is very similar to initializing a variable. The only difference is that we have to separate each value using a comma and then enclose them inside square brackets [ ].
Let’s have a look at this code snippet.
var football_players = ["Mohamed Salah", "Cristiano Ronaldo", "Lionel Messi"];
Here, the index of each array element is as follow:
You can access the contents of an array at any time just like a normal variable.
console.log( football_players );
To access a specific element from an array, we have to specify the array name and the index of that specific item. As we already created an array in the previous section, so let’s display the second item (e.g. “Cristiano Ronaldo”) from it.
console.log( football_players[1] );
Output
Cristiano Ronaldo
Updating an array item is as simple as accessing it using array name and index and then assigning it a new value.
football_players[2] = "Kaka";
Now, the third element of the football_players array has the value Kaka instead of Lionel Messi.
There is a function called
splice()
in JavaScript through which we can easily add/remove array items. It accepts three arguments index, delete_how_many_items, and then a list_of_new_items.
For now, we are only interested in deleting a specific array element. To do so, provide the index of that element and the number of elements to be deleted. In our case, it will be one.
Let’s delete the second item from the array football_players.
football_players.splice(1, 1);
At this point, our array will only have two elements which are as follow:
In JavaScript, we often use built-in array functions to perform different computations. There are so many available options. But, for the sake of this tutorial, I will discuss the most common ones.
While working on a project, sometimes we have to confirm whether a particular storage item (e.g. variable or object) is an array or not. We can achieve that with the help of the
isArray()
function.
It accepts one object as a parameter and returns true if it is an array or else false.
For example, the below code will return true because
football_players
is an array.
Array.isArray( football_players );
It’s like a loop that executes a defined set of statements for each array element.
First of all, we will define a function that displays the names of football players. Then, call this function for each element of the array using
forEach()
Let’s have a look at this code snippet.
function display_player_name(item, index) { console.log(item); } football_players.forEach( display_player_name );
It is used to check whether a specific element exists in an array or not.
includes()
will return true if an exact match item is found in the array, otherwise false.
It is mostly useful in conditional statements where we have to perform some task based on the availability of specific value in the array.
This code will return false because we don’t have “Neymar Jr.” in the
football_players
array.
football_players.includes("Neymar Jr.");
This function tries to find a specific element in the array. In case the element is found, it will return its array index. A strange thing about this function is that it will return -1 if an element doesn’t exist.
football_players.indexOf("Cristiano Ronaldo");
The above code will return -1 because previously we deleted “Cristiano Ronaldo” from our array.
As its name suggests, this function is used to arrange the elements of an array in ascending or descending order.
The below-mentioned code will sort the
football_players
array in ascending order.
football_players.sort();
There are some scenarios where you have to display the elements of an array in reverse order. Fortunately, JavaScript is packed with a reverse() function that quickly reverses the position of array elements.
It can be used with the
sort()
function to toggle the ascending and descending order. For example, instead of using
sort()
every time, it is better to call
sort()
once and then use
reverse()
for better performance.
football_players.reverse();
Arrays provide a well-structured format to store values. But, sometimes we need the data as a string.
For example, let’s say we have students result in an array and we want to convert it into a CSV format (e.g. Microsoft Excel). To do so, we have to use the
toString()
function because it will transform the array into Comma-separated values.
football_players.toString();
Instead of using a lot of variables, a better and more manageable way is to make use of JavaScript arrays. It brings a lot more possibilities to work with structured data.
In this tutorial, you learned about the basic concept of arrays in JavaScript. Later, I also introduced some commonly used array functions that enhance the overall workflow.