Introduction to Arrays in JavaScript

The array is a commonly used tool for storing data in a structured collection. There are two different syntaxes for creating arrays in JavaScript:

javascript
1let arr = new Array("Apple", "Orange", "Banana");
2
3console.log(arr);
text
1[ 'Apple', 'Orange', 'Banana' ]

Don't forget the keyword new here. This is different from how we created strings using String() or created numbers with Number(). Array is not a primitive data type, it is a special kind of object, and new is how we can create a new instance of an object in JavaScript.

If this doesn't make sense, don't worry, we will get back to this topic after we've discussed objects and the Object-Oriented Programming. For now, you only need to be familiar with the syntax.

The second method to create an array is to use a pair of square brackets, which is also referred to as the array literal:

javascript
1let arr = ["Apple", "Orange", "Banana"];
2
3console.log(arr);
text
1[ 'Apple', 'Orange', 'Banana' ]

In most cases, the second syntax is used as it is the most convenient.

The elements inside the array can be any data type you want. For example, here is an array with numbers, BigInt, strings, Boolean values, null, undefined, arrays, objects, and even functions:

javascript
1// prettier-ignore
2let arr = [
3  100,                   // Number
4  999999999999999999n,   // BigInt
5  "Qwerty",              // String
6  null,                  // null
7  undefined,             // undefined
8  [1, 2, 3],             // Array
9  { name: "John Doe" },  // Object
10  function doNothing() { // Function
11    return null;
12  },
13];
14
15console.log(arr);
text
1[
2  100,
3  999999999999999999n,
4  'Qwerty',
5  null,
6  undefined,
7  [ 1, 2, 3 ],
8  { name: 'John Doe' },
9  [Function: doNothing]
10]

Accessing an array element

You can retrieve an array element by specifying its index number.

javascript
1let arr = [5, 6, 7, 8];
2
3console.log(arr[0]);
4console.log(arr[1]);
5console.log(arr[2]);
6console.log(arr[3]);
text
15
26
37
48

It is important to note that the index starts from 0, not 1, so a[0] points to the first element, a[1] points to the second element, and so on.

Alternatively, you can use the at() method associated with arrays. For instance,

javascript
1let arr = [5, 6, 7, 8];
2
3console.log(arr.at(0));
4console.log(arr.at(1));
5console.log(arr.at(2));
6console.log(arr.at(3));

The at() method works the same as the arr[<index>] syntax, except when you need to retrieve the last item in the array.

Most other programming languages offer what is called the negative indexing, which allows you to retrieve the last item in an array with arr[-1], but that is not possible in JavaScript. So for a long time, people's solution was to use the length of the array like this:

javascript
1let arr = [5, 6, 7, 8];
2
3console.log(arr[arr.length - 1]);
text
18

arr.length gives the number of elements in the array, which is 4 in this case. But remember the index starts from 0, so the index of the last item should be arr.length - 1, which gives 3.

Recently, the at() method was introduced to offer an easier solution, allowing you to use at(-1) to access the last item.

javascript
1let arr = [5, 6, 7, 8];
2
3console.log(arr.at(-1));
text
18

You can also change an array element using the assignment operator (=).

javascript
1let a = [5, 6, 7, 8];
2
3a[1] = 100;
4
5console.log(a);
text
1[ 5, 100, 7, 8 ]

Adding and removing array elements

Besides at(), there are also methods that enable you to add or remove elements from the array.

  • pop()

The pop() method removes the last item from the end of the array.

javascript
1let arr = ["Apple", "Orange", "Banana"];
2
3arr.pop();
4
5console.log(arr);
text
1[ 'Apple', 'Orange' ]
  • push()

The push() method adds new items to the end of the array.

javascript
1let arr = ["Apple", "Orange", "Banana"];
2
3arr.push("Plum");
4
5console.log(arr);
text
1[ 'Apple', 'Orange', 'Banana', 'Plum' ]
  • shift()

The shift() method removes the first element from the beginning of the array, and then shifts all other elements to lower indexes.

javascript
1let arr = ["Apple", "Orange", "Banana"];
2
3arr.shift();
4
5console.log(arr);
text
1[ 'Orange', 'Banana' ]
  • unshift()

The unshift() method moves all elements to higher indexes, and add a new item to the beginning of the array.

javascript
1let arr = ["Apple", "Orange", "Banana"];
2
3arr.unshift("Plum");
4
5console.log(arr);
text
1[ 'Plum', 'Apple', 'Orange', 'Banana' ]

In practice, the shift() and unshift() methods are much slower compared to pop() and push(), due to the shifting of the array elements. If possible, you should avoid working at the beginning of the array, and only use pop() and push() in your code.

Concatenating arrays

JavaScript also allows you to concatenate multiple arrays together into one array using the concat() method. For example,

javascript
1let arr1 = ["Apple", "Orange", "Banana"];
2let arr2 = ["Plum", "Peach", "Pear"];
3
4arr1 = arr1.concat(arr2);
5
6console.log(arr1);
text
1[ 'Apple', 'Orange', 'Banana', 'Plum', 'Peach', 'Pear' ]

The concat() method also enables you to join more than two arrays.

javascript
1let arr1 = ["Apple", "Orange", "Banana"];
2let arr2 = ["Plum", "Peach"];
3let arr3 = ["Pear"];
4
5arr1 = arr1.concat(arr2, arr3);
6
7console.log(arr1);
text
1[ 'Apple', 'Orange', 'Banana', 'Plum', 'Peach', 'Pear' ]

Alternatively, you can use the spread syntax (...).

javascript
1let arr1 = ["Apple", "Orange", "Banana"];
2let arr2 = ["Plum", "Peach"];
3let arr3 = ["Pear"];
4
5let arr = [...arr1, ...arr2, ...arr3];
6
7console.log(arr);
text
1[ 'Apple', 'Orange', 'Banana', 'Plum', 'Peach', 'Pear' ]

Searching arrays

  • indexOf() and lastIndexOf()

Using the indexOf() method, you can locate the first occurrence of the given item in the array.

javascript
1let arr = ["Apple", "Orange", "Orange"];
2
3console.log(arr.indexOf("Orange"));
text
11

Notice that there are two "Orange"s in this array, but only the location of its first occurrence is returned.

If the element does not exist in the array, the method will return -1.

javascript
1let arr = ["Apple", "Orange", "Banana"];
2
3console.log(arr.indexOf("Peach"));
text
1-1

lastIndexOf() is the opposite of indexOf(). It returns the location of the last occurrence of the item.

javascript
1let arr = ["Apple", "Orange", "Orange"];
2
3console.log(arr.lastIndexOf("Orange"));
text
12

Similarly, if the element does not exist in the array, -1 will be returned.

javascript
1let arr = ["Apple", "Orange", "Orange"];
2
3console.log(arr.lastIndexOf("Peach"));
text
1-1
  • find()

find() is one of the more advanced methods for arrays, as it searches the array based on a test function. If you are new to programming, and have no idea what a function is, you can go through the function lessons first, and then come back to this topic.

javascript
1let arr = [23, -5, 667, 1, -3, 6, 17, -69];
2
3let answer = arr.find(testFunction);
4
5// This example test function finds the first array element that is greater than 50
6function testFunction(value, index, array) {
7  return value > 50;
8}
9
10console.log(answer);
text
1667

The find() method will pass each item in the array to the test function, and the first element that passes the test will be returned.

The test function should accept three arguments, value, which corresponds to each element in the array, index, the index number of that element, and array, which is the entire array.

You will encounter many more helper functions like this that accept a predefined list of arguments, and some of them might be difficult to understand. In this case, you could print them out into the console using console.log(). This would help you understand what they are, and what you can do with them.

javascript
1let arr = [23, -5, 667, 1, -3, 6, 17, -69];
2
3let answer = arr.find(testFunction);
4
5// This example test function finds the first array element that is greater than 50
6function testFunction(value, index, array) {
7  console.log(`Value: ${value}`);
8  console.log(`Index: ${index}`);
9  console.log(`Array: ${array}`);
10  console.log("\n");
11
12  return value > 50;
13}
14
15console.log(answer);
text
1Value: 23
2Index: 0
3Array: 23,-5,667,1,-3,6,17,-69
4
5
6Value: -5
7Index: 1
8Array: 23,-5,667,1,-3,6,17,-69
9
10
11Value: 667
12Index: 2
13Array: 23,-5,667,1,-3,6,17,-69
  • filter()

The filter() method is similar to find(), except instead of returning a single value that passes the test, filter() returns an array of values.

javascript
1let arr = [23, -5, 667, 150, -3, 60, 17, -69];
2
3let answer = arr.filter(testFunction);
4
5function testFunction(value, index, array) {
6  return value > 50;
7}
8
9console.log(answer);
text
1[ 667, 150, 60 ]
  • every()

The every() method iterates over the entire array, and examines if the element passes a test. If all element passes, every() returns true, and if not, every() returns false.

javascript
1let arr = [1, 2, 3, 4, 5];
2
3let answer = arr.every(testFunction);
4
5// Check if all elements are greater than 0
6function testFunction(value, index, array) {
7  return value > 0;
8}
9
10console.log(answer);
text
1true
  • includes()

The includes() method tests if a given value exists in the array.

javascript
1let arr = [1, 2, 3, 4, 5];
2
3let answer = arr.includes(100);
4
5console.log(answer);
text
1false

You can also provide an index, which tells the includes() method to check if the value exists at the exact index.

javascript
1let arr = [100, 2, 3, 4, 5];
2
3let answer = arr.includes(100, 2);
4
5console.log(answer);
text
1false

Notice that even though 100 exists in the array, it does not exist at the index 2, so the method returns false.

Sorting arrays

JavaScript offers four different methods that allow you to sort the array, sort(), toSorted(), reverse(), and toReversed().

Sorting strings

By default, these methods are used to sort arrays with string values.

  • sort() will sort the array alphabetically.
javascript
1let arr = ["Apple", "Orange", "Banana"];
2
3arr.sort();
4
5console.log(arr);
text
1[ 'Apple', 'Banana', 'Orange' ]
  • reverse() will reverse the array.
javascript
1let arr = ["Apple", "Orange", "Banana"];
2
3arr.reverse();
4
5console.log(arr);
text
1[ 'Banana', 'Orange', 'Apple' ]
  • toSorted() is just like sort(), except it returns the sorted result without altering the original array.
javascript
1let arr = ["Apple", "Orange", "Banana"];
2
3let sortedArr = arr.toSorted();
4
5console.log(sortedArr);
6console.log(arr);
text
1[ 'Apple', 'Banana', 'Orange' ]
2[ 'Apple', 'Orange', 'Banana' ]
  • toReversed() method is just like reverse(), except it returns the sorted result without altering the original array.
javascript
1let arr = ["Apple", "Orange", "Banana"];
2
3let sortedArr = arr.toReversed();
4
5console.log(sortedArr);
6console.log(arr);
text
1[ 'Banana', 'Orange', 'Apple' ]
2[ 'Apple', 'Orange', 'Banana' ]

Sorting numbers

The sort() method can also be used to sort numbers, but it requires a bit more customization. Because by default, these methods will convert the numbers into strings, and then sort them alphabetically, which would give results like this:

javascript
1let arr = [2, -1, 45, 3, 21, 17, 9, 20];
2
3console.log(arr.toSorted());
text
1[ -1, 17,  2, 20, 21,  3, 45,  9 ]

To sort numbers, you must pass a compare function.

javascript
1let arr = [2, -1, 45, 3, 21, 17, 9, 20];
2
3arr.sort(compareFunction);
4
5function compareFunction(a, b) {
6  return a - b;
7}
8
9console.log(arr);
text
1[ -1,  2,  3,  9, 17, 20, 21, 45 ]

The compare function takes two input values, a and b, and return either a positive value, a negative value, or 0. The function compares all the values in the array, two numbers at a time.

  • If the function returns positive, b will be placed before a.
  • If the function returns negative, a will be placed before b.
  • If the function returns 0, no changes will be made.

This example sorts the array in an ascending order. To sort in the descending order, simply make the compare function return b - a.

javascript
1let arr = [2, -1, 45, 3, 21, 17, 9, 20];
2
3arr.sort(compareFunction);
4
5function compareFunction(a, b) {
6  return b - a;
7}
8
9console.log(arr);
text
1[ 45, 21, 20, 17, 9,  3,  2, -1 ]

Iterating over an array

Another operation we often perform on arrays is iterating over all of its values. The most straightforward way to do this is with a loop. If you don't know what a loop is, please go through the linked lesson first.

Using loops

Take a look at this example:

javascript
1for (let i = 0; i < a.length; i++) {
2  . . .
3}

let i = 0 initiates the variable i which will be the index number of each array element. The index i starts from 0. i will increment by 1 for every iteration (i++, which is a shorthand for i = i + 1), until it reaches a.length.

a.length is the length of the array, which means the loop will terminate when i equals a.length - 1. Because for the next iteration, i will become a.length, which violates the condition i < a.length.

Besides using the index, you can also access each array element with a for of loop, which looks like this:

javascript
1let arr = [2, -1, 45, 3, 21, 17, 9, 20];
2
3for (let ele of arr) {
4  console.log(ele);
5}
text
12
2-1
345
43
521
617
79
820

Using methods

There are also two built-in methods in JavaScript that allow you to iterate over the array without having to use a loop. This is one of the greatest features in JavaScript, because for most other programming languages, you will have to create the loop yourself.

The first method is forEach(). Here is an example of calculating the sum of all array elements using the forEach() method.

javascript
1let arr = [2, -1, 45, 3, 21, 17, 9, 20];
2let sum = 0;
3
4arr.forEach(calcSum);
5
6function calcSum(value, index, array) {
7  sum = sum + value;
8}
9
10console.log(sum);
text
1116

If you would like to perform some actions to each array element, and then return the transformed result, use the map() method. For example, here we are using map() to return an array whose elements are the square of the original value.

javascript
1let arr = [2, -1, 45, 3, 21, 17, 9, 20];
2let sum = 0;
3
4let squared = arr.map(calcSum);
5
6function calcSum(value, index, array) {
7  return value ** 2;
8}
9
10console.log(squared);
11console.log(arr);
text
1[ 4, 1, 2025, 9, 441, 289, 81, 400 ]
2[ 2, -1, 45,  3, 21, 17,  9, 20 ]

The map() method will return a new array with the transformed elements, and the original will not be changed.

Matrix

Matrix is a concept that exists in both mathematics and computer science. It is defined as a two dimensional array with its elements arranged in rows and columns like this:

Matrix

It is possible for you to create such a structure using JavaScript by putting several smaller arrays inside a bigger array.

javascript
1let matrix = [
2  [1, 2, 3],
3  [4, 5, 6],
4  [7, 8, 9],
5];

To retrieve an element from this matrix, you need to specify two indexes, matrix[<row>][<col>].

javascript
1console.log(matrix[0][1]); // -> 2
2console.log(matrix[1][0]); // -> 4
3console.log(matrix[2][2]); // -> 9