JavaScript arrays
// updated 2025-05-06 14:01
Arrays refer to lists or collections of related objects...
In JavaScript, this would consist of comma-separated values, all encapsulated with square brackets:
1const myArray = [ 1, 2, "something", true, anotherVariable]
Notice how in JavaScript we can include objects of different types (such as numbers, strings, Booleans and objects) into the same array. Other programming languages might not allow us to do this!
In this article, we will cover the following topics:
- Creating arrays
- Adding elements (items) to arrays
- Accessing elements
- Converting arrays to strings
- Finding an array's length
- Looping through arrays
- Extracting an array's last element (pop method)
- Extracting an array's first element (shift method)
- Multi-dimensional arrays
- Destructuring arrays
- Searching arrays (indexOf and includes methods)
- Manipulating array elements (splice method)
- Copying arrays (concat / slice / ...spread)
Creating arrays
The example above shows how we can create an array in JavaScript (and assign it to a variable name).
At the most basic, we can create an empty array like this:
1const myArray = []
Adding elements to arrays
Whether we have an empty array or a filled array, we can add elements (items) individually in at least three ways:
- assigning a value to
arrayName[index]
- where
index
is any positive integer
- where
- calling
push(value)
- inserts the new element at the end of the array
- calling
unshift(value)
- inserts the new element at the beginning of the array
Assigning a value to arrayName[index]
This assumes that we have full view of the array's elements:
1// start with an empty array
2const myArray = []
3
4// let's add 4 elements, line by line
5myArray[0] = 1
6myArray[1] = 2
7myArray[2] = "something"
8myArray[3] = true
9
10// print it out
11console.log(myArray)
12// 1, 2, "something", true
Also, note that the first element has an index of 0!
Calling push(value)
This adds the element to the end of the array:
1myArray.push("another thing")
2console.log(myArray)
3// 1, 2, "something", true, "another thing"
4
5myArray.push("yet another thing")
6console.log(myArray)
7// 1, 2, "something", true, "another thing", "yet another thing"
Calling unshift(value)
This adds the element to the beginning of the array:
1const newArray = [ 0, 1, 2, "three", 4 ]
2
3newArray.unshift("another thing")
4
5console.log(myArray)
6// [ "another thing", 0, 1, 2, "three", 4 ]
Accessing array elements
We can also use the arrayName[index]
notation to access array objects:
1const myArray = [ 1, 2, "something", true]
2console.log(myArray[2])
3// "something"
Converting arrays to strings
If we have an array and wish to print out all of its elements, we first convert it to a string:
1const myArray = [ 1, 2, "something", true ]
2
3const myArrayString = myArray.toString()
4
5console.log(myArrayString)
6// 1,2,something,true
We can also use the join()
method to convert an array into a string, then fuse the elements with any arbitrary character(s), such as a comma or a space or a plus sign or whatever:
1const myArray = [1, 2, "something", true ]
2
3const myArrayJoined = myArray.join(" + ")
4
5console.log(myArrayJoined)
6// 1 + 2 + something + true
If we do not provide an argument for join()
then the elements will be fused with commas with no spaces:
1const myArray = [1, 2, "something", true ]
2
3const myArrayJoined = myArray.join()
4
5console.log(myArrayJoined)
6// 1,2,something,true
Finding the length of an array
To find the length (number of elements) of an array, we can use an array property called length
:
1const myArray = [ 1, 2, "something", true ]
2console.log(myArray.length)
3// 4
Looping through arrays
To iterate through array elements, i.e. to get all of its items, we can use a for
loop:
1const myArray = [ 1, 2, "something", true ]
2
3// print out each array item on its own line
4for (let i = 0; i < myArray.length; i++) {
5 console.log(myArray[i])
6}
Also, we can use a for ... of ...
loop to simplify the for
loop:
1const myArray = [1, 2, "something", true]
2
3for (const item of myArray) {
4 console.log(item)
5}
6
7/* Output:
81
92
10"something"
11true
Finally, we can use a function called map
but we will cover the details of map
on another page:
1const myArray = [ 1, 2, "something", true ]
2
3// print out each item on its own new line
4myArray.map(item => {
5 console.log(item)
6})
Extracting an array's last element (pop method)
To get an array's last item, we can use this built-in method for arrays called pop()
:
1const myArray = [ 1, 2, "something", true ]
2const lastElement = myArray.pop()
3
4// the last element gets removed from the original array
5console.log(myArray)
6// [ 1, 2, "something" ]
7
8// the variable lastElement gets assigned the last element
9console.log(lastElement)
10// true
The original array changes when using this method!
Extracting an array's first element (shift method)
To get an array's first item, we can use this build-in method for arrays called shift()
:
1const myArray = [ 1, 2, "something", true ]
2const firstElement = myArray.shift()
3
4// the first element gets removed from the original array
5console.log(myArray)
6// [ 2, "something", true ]
7
8// the variable firstElement gets assigned the last element
9console.log(firstElement)
10// 1
As with pop()
, the original array changes when using shift()
!
Multi-dimensional arrays
We can think of a two-dimensional array as just a table (or in algebra, a matrix), with rows and columns!
A chessboard is a good example of a matrix:
1let chessboard = [
2 ["R", "N", "B", "Q", "K", "B", "N", "R"],
3 ["P", "P", "P", "P", "P", "P", "P", "P"],
4 [" ", " ", " ", " ", " ", " ", " ", " "],
5 [" ", " ", " ", " ", " ", " ", " ", " "],
6 [" ", " ", " ", " ", " ", " ", " ", " "],
7 [" ", " ", " ", " ", " ", " ", " ", " "],
8 ["p", "p", "p", "p", "p", "p", "p", "p"],
9 ["r", "n", "b", "q", "k", "b", "n", "r"]
10]
We would then access an element using double square bracket notation like this:
1console.log(chessboard[0][3])
2// "Q"
The former set of square brackets denotes the row, while the latter denotes the column!
Destructuring arrays
In a technique called destructuring, we can "take apart" an array and place the parts into variables - for example, in our chessboard
example from above, we can use the following syntax:
1let [firstRow, secondRow] = chessboard
2// firstRow and secondRow are just variable names
3// (they are not special/reserved keywords)
4
5console.log(firstRow)
6// ["R", "N", "B", "Q", "K", "B", "N", "R"]
7
8console.log(secondRow)
9// ["P", "P", "P", "P", "P", "P", "P", "P"]
Note that we do not have to include all of the elements in the array! We can even skip elements by placing a blank space in between commas like this:
1let [firstRow, secondRow, , , , , seventhRow, eighthRow] = chessboard
2
3console.log(seventhRow)
4// ["p", "p", "p", "p", "p", "p", "p", "p"]
5
6console.log(eighthRow)
7// ["r", "n", "b", "q", "k", "b", "n", "r"]
Searching within arrays
Much like a string, we can use the array version of the built-in indexOf()
method to see if a value exists inside an array:
1let myArray = [ "item", 300, -11, "something", true, true, true ]
2
3console.log(myArray.indexOf(300))
4// 1
5// i.e. the second element of the array
6
7console.log(myArray.indexOf(true))
8// 4
9// i.e. the first occurrence of true in the array
10
11console.log(myArray.indexOf("not here"))
12// -1
13// it will return -1 if value is not found
The indexOf()
method also comes with an optional parameter, which allows us to search from (and including) a specific index in the array:
1let myArray = [ "item", true, 300, -11, "something", 300, true ]
2
3console.log(myArray.indexOf(300, 2))
4// 2
5// i.e. the third element of the array
6
7console.log(myArray.indexOf(300, 3))
8// 5
9// i.e. the sixth element;
10// indexOf searches at or after the (3+1)th element
11
12console.log(myArray.indexOf(true, 4))
13// 6
14// i.e. the last element (myArray.length - 1)
Also very similar to the string's built-in indexOf()
method, includes()
returns a Boolean that specifies whether an array has an element with a certain value:
1let myArray = [ "a", "b", "C", "d", 2 ]
2
3console.log(myArray.includes("C")
4// true
5
6console.log(myArray.includes("c")
7// false
8// includes() is case sensitive!
9
10console.log(myArray.includes("2")
11// false
12// "2" is not in the array but 2 is!
As we can gather from the above, the includes()
method is both case-sensitive and type-sensitive!
Manipulating array elements (splice method)
Not to confuse with slice()
, the splice()
method allows us to "do surgery" on an array by:
- looking at a starting index
- removing a specified number of elements
- adding some values in their place
1let myArray = [ "first", "second", "third", "fourth", "fifth" ]
2
3myArray.splice(2, 1, "tooth", "both")
4console.log(myArray)
5// [ "first", "second", "tooth", "both", "fourth", "fifth" ]
6// starting from index 2, remove the next 1 item(s)
7// then, in their place(s), add "tooth" and "both"
8
9myArray.splice(3, 2, "moth")
10// [ "first", "second", "tooth", "moth", "fifth" ]
11// continue from the mutated array
12// starting from index 3, remove the subsequent 2 items
13// then, in their places, add "moth"
The original array will mutate (change)!
In general, the splice()
method consists of:
1theArray.splice(startIndex, numberOfItemsToRemove, additionalItem1, additionalItem2, ...)
Starting from the third argument, additionalItem1
can be followed by infinite elements!
Copying arrays
How not to copy an array
An obvious way to copy an array might seem like this:
1let originalArray = [1, 2, 3]
2let copiedArray = myArray
However, any change in the copiedArray
would result in a change in the original array:
1copiedArray[0] = -1
2
3console.log(originalArray[0])
4// -1 (not 1)
We call this phenomenon deep copying: a change in one copy also results in a change for the original. To perform shallow copying (i.e. one where each copy is actually its own thing), we would use some other methods:
- concat
- slice
- spread
Using concat()
We would use this method on an empty array and feed the original array as an argument:
1let originalArray = [1, 2, 3]
2let copiedArray = [].concat(originalArray)
3
4console.log(copiedArray)
5// [1, 2, 3]
6
7copiedArray[0] = -1
8console.log(originalArray[0])
9// 1 (not -1!)
Using slice()
We would use this method on the original array with no argument:
1let originalArray = [1, 2, 3]
2let copiedArray = originalArray.slice()
3
4console.log(copiedArray)
5// [1, 2, 3]
6
7copiedArray[0] = -1
8console.log(originalArray[0])
9// 1 (not -1!)
Using the spread operator
We would take an empty array and use this syntax, ...originalArray
, on the original array:
1let originalArray = [1, 2, 3]
2let copiedArray = [...originalArray]
3
4console.log(copiedArray)
5// [1, 2, 3]
6
7copiedArray[0] = -1
8console.log(originalArray[0])
9// 1 (not -1!)
As we can see, a lot can happen with arrays! Much of computer programming involves these list-like structures. If we think about it, much of our lives involves lists, or collections of items. Thus, we will spend a lot of time working with arrays!