JavaScript arrays

collecting several items in one container
// 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:

const 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:

const 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
  • 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:

// start with an empty array
const myArray = []

// let's add 4 elements, line by line
myArray[0] = 1
myArray[1] = 2
myArray[2] = "something" 
myArray[3] = true

// print it out
console.log(myArray)
// 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:

myArray.push("another thing")
console.log(myArray)
// 1, 2, "something", true, "another thing"

myArray.push("yet another thing")
console.log(myArray)
// 1, 2, "something", true, "another thing", "yet another thing"

Calling unshift(value)

This adds the element to the beginning of the array:

const newArray = [ 0, 1, 2, "three", 4 ]

newArray.unshift("another thing")

console.log(myArray)
// [ "another thing", 0, 1, 2, "three", 4 ]

Accessing array elements

We can also use the arrayName[index] notation to access array objects:

const myArray = [ 1, 2, "something", true]
console.log(myArray[2]) 
// "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:

const myArray = [ 1, 2, "something", true ]

const myArrayString = myArray.toString()

console.log(myArrayString)
// 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:

const myArray = [1, 2, "something", true ]

const myArrayJoined = myArray.join(" + ") 

console.log(myArrayJoined)
// 1 + 2 + something + true

If we do not provide an argument for join() then the elements will be fused with commas with no spaces:

const myArray = [1, 2, "something", true ]

const myArrayJoined = myArray.join()

console.log(myArrayJoined)
// 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:

const myArray = [ 1, 2, "something", true ]
console.log(myArray.length)
// 4

Looping through arrays

To iterate through array elements, i.e. to get all of its items, we can use a for loop:

const myArray = [ 1, 2, "something", true ]

// print out each array item on its own line
for (let i = 0; i < myArray.length; i++) {
  console.log(myArray[i])
}

Also, we can use a for ... of ... loop to simplify the for loop:

const myArray = [1, 2, "something", true]

for (const item of myArray) {
  console.log(item)
}

/* Output:
1
2
"something"
true

Finally, we can use a function called map but we will cover the details of map on another page:

const myArray = [ 1, 2, "something", true ]

// print out each item on its own new line
myArray.map(item => {
  console.log(item)
})

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():

const myArray = [ 1, 2, "something", true ]
const lastElement = myArray.pop()

// the last element gets removed from the original array
console.log(myArray)
// [ 1, 2, "something" ]

// the variable lastElement gets assigned the last element
console.log(lastElement)
// 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():

const myArray = [ 1, 2, "something", true ]
const firstElement = myArray.shift()

// the first element gets removed from the original array
console.log(myArray)
// [ 2, "something", true ]

// the variable firstElement gets assigned the last element
console.log(firstElement)
// 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:

let chessboard = [
  ["R", "N", "B", "Q", "K", "B", "N", "R"],
  ["P", "P", "P", "P", "P", "P", "P", "P"],
  [" ", " ", " ", " ", " ", " ", " ", " "],
  [" ", " ", " ", " ", " ", " ", " ", " "],
  [" ", " ", " ", " ", " ", " ", " ", " "],
  [" ", " ", " ", " ", " ", " ", " ", " "],
  ["p", "p", "p", "p", "p", "p", "p", "p"],
  ["r", "n", "b", "q", "k", "b", "n", "r"]
]

We would then access an element using double square bracket notation like this:

console.log(chessboard[0][3])
// "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:

let [firstRow, secondRow] = chessboard
// firstRow and secondRow are just variable names 
// (they are not special/reserved keywords)

console.log(firstRow)
// ["R", "N", "B", "Q", "K", "B", "N", "R"]

console.log(secondRow)
// ["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:

let [firstRow, secondRow, , , , , seventhRow, eighthRow] = chessboard

console.log(seventhRow)
// ["p", "p", "p", "p", "p", "p", "p", "p"]

console.log(eighthRow)
// ["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:

let myArray = [ "item", 300, -11, "something", true, true, true ]

console.log(myArray.indexOf(300))
// 1 
// i.e. the second element of the array

console.log(myArray.indexOf(true))
// 4
// i.e. the first occurrence of true in the array

console.log(myArray.indexOf("not here"))
// -1
// 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:

let myArray = [ "item", true, 300, -11, "something", 300, true ]

console.log(myArray.indexOf(300, 2))
// 2
// i.e. the third element of the array

console.log(myArray.indexOf(300, 3))
// 5
// i.e. the sixth element; 
// indexOf searches at or after the (3+1)th element

console.log(myArray.indexOf(true, 4))
// 6
// 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:

let myArray = [ "a", "b", "C", "d", 2 ]

console.log(myArray.includes("C")
// true

console.log(myArray.includes("c")
// false
// includes() is case sensitive!

console.log(myArray.includes("2")
// false 
// "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
let myArray = [ "first", "second", "third", "fourth", "fifth" ]

myArray.splice(2, 1, "tooth", "both")
console.log(myArray)
// [ "first",  "second", "tooth", "both", "fourth", "fifth" ]
// starting from index 2, remove the next 1 item(s)
// then, in their place(s), add "tooth" and "both"

myArray.splice(3, 2, "moth")
// [ "first", "second", "tooth", "moth", "fifth" ]
// continue from the mutated array
// starting from index 3, remove the subsequent 2 items
// then, in their places, add "moth"

The original array will mutate (change)!

In general, the splice() method consists of:

theArray.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:

let originalArray = [1, 2, 3]
let copiedArray = myArray

However, any change in the copiedArray would result in a change in the original array:

copiedArray[0] = -1

console.log(originalArray[0])
// -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:

let originalArray = [1, 2, 3]
let copiedArray = [].concat(originalArray)

console.log(copiedArray)
// [1, 2, 3]

copiedArray[0] = -1
console.log(originalArray[0])
// 1 (not -1!)

Using slice()

We would use this method on the original array with no argument:

let originalArray = [1, 2, 3]
let copiedArray = originalArray.slice()

console.log(copiedArray)
// [1, 2, 3]

copiedArray[0] = -1
console.log(originalArray[0])
// 1 (not -1!)

Using the spread operator

We would take an empty array and use this syntax, ...originalArray, on the original array:

let originalArray = [1, 2, 3]
let copiedArray = [...originalArray]

console.log(copiedArray)
// [1, 2, 3]

copiedArray[0] = -1
console.log(originalArray[0])
// 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!

⬅️ older (in textbook-javascript)
📒 JavaScript objects and JSON
newer (in textbook-javascript) ➡️
JavaScript higher-order functions 📒
⬅️ older (in code)
📒 JavaScript objects and JSON
newer (in code) ➡️
JavaScript higher-order functions 📒
⬅️ older (posts)
📒 JavaScript objects and JSON
newer (posts) ➡️
JavaScript higher-order functions 📒