An array is a JavaScript list-like object that can store multiple values in a single variable. It is an ordered collection of values where each value is called an element with a pre-defined numeric position in the array, referred to as its index.
A JavaScript array can store different data types in one box: strings, boolean, numbers, HTML elements, objects, or even other arrays.
Like other programming languages like Java and Python, arrays in JavaScript are zero-based. It means that the first element in the collection has an index of 0, the second element has an index of 1, the third element has an index of 2, and so on.
Create a new array
There are two ways to create an array in JavaScript. The simplest way to create an array is using the array literal notation:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
Alternatively, you could use the global Array
class constructor to initialize a new array:
const fruits = new Array('Apple', 'Orange', 'Mango', 'Banana')
To create an empty array, use the empty brackets:
const animals = []
Spaces and line breaks are permitted. An array declaration can span multiple lines:
const fruits = [
'Apple',
'Orange',
'Mango',
'Banana'
]
If you know, in advance, the number of elements the array will contain, you can use the count as an argument to the Array
constructor. An empty array will automatically be created with the specified number of slots initialized with the value undefined
:
const numbers = new Array(50)
An array can store elements of any type: strings, numbers, functions, objects, and even other arrays:
const arr = [
'Tiger',
29.6,
{ name: 'John Doe', age: 29 },
true,
function () {
console.log('Hey there!')
},
['Apple', 'Banana']
]
Get an element from an array
You can access an array element by its index number in square brackets:
const animals = ['🐱', '🐭', '🐧', '🐯', '🐘']
console.log(animals[1]) // 🐭
console.log(animals[3]) // 🐯
Note that an array index starts at 0
and not 1
. This means that the first element has an index of 0
, and the last element has an index of array length minus 1
. The above array of five elements has indexes starting from 0
to 4
.
A JavaScript array can be multi-dimensional, which means that an array element can contain another array whose elements can have arrays, and so on. To access an element from a multi-dimensional array, you need to specify the index multiple times:
const users = [
['John Doe', 22],
['Lisa Lee', 33],
[
['Alex', 'USA'],
['Tom Doe', 'DE']
]
]
console.log(users[1][0]) // Lisa Lee
console.log(users[2][0]) // ['Alex', 'USA']
console.log(users[2][1][0]) // Tom Doe
Add an element to an array
The simplest way to add an element to an array is by using the push()
method:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
// add a new element
fruits.push('Cherry')
console.log(fruits)
// ['Apple', 'Orange', 'Mango', 'Banana', 'Cherry']
Alternatively, you could use the length
property to insert an element at the end of the array:
fruits[fruits.length] = 'Cherry'
Update an array element
The following example demonstrates how you can change the value of an array element:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
// change 2nd element value
fruits[1] = 'Cherry'
// print array
console.log(fruits)
// [ 'Apple', 'Cherry', 'Mango', 'Banana' ]
Delete an element from an array
Since JavaScript arrays are objects, you can use the delete
operator to delete any specific element from an array:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
// delete 2nd element
delete fruits[1]
console.log(fruits)
// ['Apple', <1 empty item>, 'Mango', 'Banana']
Since the delete
operator only resets the element value to undefined
, you shouldn't use it as it might leave holes in the array. Instead, it would be best to use the pop()
and shift()
methods explained below.
Check if a variable is an array
One of the most typical questions in JavaScript communities is how to check if the given variable is an array.
The main problem is that a JavaScript array is internally treated as a special object. The square brackets syntax used for accessing an array element arr[index]
is essentially the same as we use for an object (obj[key]
). The only visible difference is that numbers are used as keys.
Therefore, you can not use the typeof
operator as it would always return object
for an array:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
console.log(typeof fruits) // object
To truly determine whether the given variable is an array, ECMAScript 5 introduced a new method called Array.isArray()
:
Array.isArray(fruits) // true
The Array.isArray()
works in all modern browsers and Internet Explorer 9 and higher. Alternatively, you could also use the instanceof
operator to check whether the given object is an array:
fruits instanceof Array // true
The instanceof
operator is supported by Internet Explorer 6 and higher.
Get the number of elements in an array
The length
property returns the maximum numeric index plus one and not the actual count of the elements. It automatically updates when the array is modified.
Let us look at the following example to understand what I mean:
const animals = []
animals[20] = 'Cat'
console.log(animals.length) // 21
As you can see above, the array's length
property is updated to the highest index plus one when we add just a single element.
Another exciting thing about the length
property is that it is writable. You can manually set a new value to increase or decrease the size of the array. An array can be truncated by selecting a smaller length
value:
const numbers = [1, 2, 3, 4, 5]
// truncate to 3-element
numbers.length = 3
console.log(numbers) // [1, 2, 3]
// increase size to 6
numbers.length = 6
console.log(numbers) // [1, 2, 3, empty × 3]
To clear an array, set the length
property value to 0:
// clear the array
numbers.length = 0
console.log(numbers) // []
Iterate over elements of an array
There are multiple ways to iterate over array elements. The simplest way is to use the classic for
loop:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i])
}
You also use other JavaScript loops like for...of
, for...in
, and forEach()
to iterate through an array. Read this article to learn more about all available ways of looping an array in JavaScript.
Popular array methods
The array prototype provides several methods to perform traversal and mutation operations like add, remove, update, and more to arrays.
Let us look at some of the most popular methods you can use to manipulate arrays.
toString()
method
The JavaScript toString()
method converts an array to a comma-separated string:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
console.log(fruits.toString())
// Apple,Orange,Mango,Banana
join()
method
The join()
method concatenates all array elements into a string. It is very much similar to the above toString()
method but allows you to specify a separator:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
console.log(fruits.join('_'))
// Apple_Orange_Mango_Banana
concat()
method
The concat()
method creates a new array by merging two existing arrays:
const arr1 = [1, 2]
const arr2 = [3, 4]
const newArr = arr1.concat(arr2)
console.log(newArr) // [ 1, 2, 3, 4 ]
The concat()
method doesn't change the existing arrays. Instead, it always returns a new array. You can even specify more than one array of arguments:
const arr1 = [1, 2]
const arr2 = [3, 4]
const arr3 = [5, 6]
const newArr = arr1.concat(arr2, arr3)
console.log(newArr) // [ 1, 2, 3, 4, 5, 6 ]
You can also use the concat()
method to create a new array from an existing array with additional elements:
const arr1 = [1, 2]
const newArr = arr1.concat(2, 3, 4)
console.log(newArr) // [ 1, 2, 2, 3, 4 ]
push()
method
The push()
method adds one or more elements at the end of an existing array:
const names = ['Alex', 'Mike', 'Atta']
// add more elements
names.push('Ali', 'Emma')
console.log(names) // ['Alex', 'Mike', 'Atta', 'Ali', 'Emma']
The push()
method returns the updated length
of the array:
const length = names.push('Ali', 'Emma')
console.log(length) // 5
pop()
method
The pop()
method does the opposite of the push()
method. It removes the last element of an array and returns it:
const names = ['Alex', 'Mike', 'Atta']
// remove last element
const elem = names.pop()
console.log(elem) // Atta
unshift()
method
The unshift()
method adds one or more elements at the beginning of an array and unshifts older elements. This method returns the updated length of the array:
const names = ['Alex', 'Mike', 'Atta']
// add new elements at start
const length = names.unshift('Ali', 'Emma')
console.log(length) // 5
console.log(names) // ['Ali', 'Emma', 'Alex', 'Mike', 'Atta']
shift()
method
The shift()
method removes the first element of an array and returns it. All other elements are shifted to a lower index:
const names = ['Alex', 'Mike', 'Atta']
// remove an element from start
const elem = names.shift()
console.log(elem) // Alex
console.log(names) // ['Mike', 'Atta']
splice()
method
The splice()
method can be used to add new elements and remove existing elements from an array. This method modifies the original array and returns the deleted elements as an array (if any).
Here is the syntax of splice()
:
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
start
— The starting index for changing elements in the array.deleteCount
— An integer indicating the number of elements in the array to remove fromstart
.item1, item2, ...
— The elements to be added to the array, beginning fromstart
.
Removing Elements
Here is an example that uses splice()
to remove the first two elements from the beginning of an array:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
// remove first elements
const removed = fruits.splice(0, 2)
console.log(fruits) // ['Mango', 'Banana']
console.log(removed) // ['Apple', 'Orange']
If the deleteCount
is omitted, all the elements starting from start
are removed from the array:
const removed = fruits.splice(1)
console.log(fruits) // ['Apple']
console.log(removed) // ['Orange', 'Mango', 'Banana']
You can also replace the removed items with the new ones using splice()
:
const removed = fruits.splice(1, 2, 'Cherry', 'Watermelon')
console.log(fruits) // ['Apple', 'Cherry', 'Watermelon', 'Banana']
console.log(removed) // ['Orange', 'Mango']
Adding Elements
To add new elements with splice()
, just set the deleteCount
to zero:
const removed = fruits.splice(2, 0, 'Cherry')
console.log(fruits) // ['Apple', 'Orange', 'Cherry', 'Mango', 'Banana']
console.log(removed) // []
slice()
method
The slice()
method slices out a part of an array into a new array. This method returns a new array with elements copied from the initial array. The original array remains unchanged.
The slice()
method takes up to two arguments: the start index to select elements from and an optional end index (exclusive).
Here is an example:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
const sliced = fruits.slice(1, 3)
console.log(sliced) // ['Orange', 'Mango']
If the end index is omitted, slice()
will slice out the rest of the array beginning from the start index:
const sliced = fruits.slice(1)
console.log(sliced) // ['Orange', 'Mango', 'Banana']
indexOf()
method
The indexOf()
method searches the array for the given element and returns its position:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
fruits.indexOf('Orange') // 1
fruits.indexOf('Cherry') // -1 (not found)
filter()
method
The filter()
method creates a new array populated with all array elements that pass a specific condition:
const ages = [24, 45, 33, 76, 55, 86]
const above50 = ages.filter(age => age > 50)
console.log(above50) // [76, 55, 86]
The filter()
method doesn't execute the function for empty elements. Also, it doesn't change the original array.
map()
method
The map()
method creates a new array with the results of executing a function for each element in the array:
const prices = [10, 9.99, 15, 45]
const updated = prices.map(price => '$' + price)
console.log(updated) // ['$10', '$9.99', '$15', '$45']
reduce()
method
The reduce()
method reduces the array to a single value. It calls the provided function for each element left to right except empty values. The return value of the function is stored in an accumulator.
The reduce()
method is commonly used for calculating totals like sum, average, minimum and maximum values in an array.
Here is an example that calculates the sum of all elements in an array by using the reduce()
method:
const numbers = [10, 99, 75, 45, 33]
const sum = numbers.reduce((total, num) => total + num)
console.log(sum) // 262
You can also pass an optional initial value of accumulator to the reduce()
method:
// pass initial value 100
const sum = numbers.reduce((total, num) => total + num, 100)
console.log(sum) // 362
forEach()
method
The forEach()
method iterates over all elements of an array using a callback function once for each element, in order:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
fruits.forEach((fruit, index) => {
console.log(`${fruit} has ${index} index.`)
})
// Apple has 0 index.
// Orange has 1 index.
// Mango has 2 index.
// Banana has 3 index.
Take a look at this guide to learn more about the forEach()
method in JavaScript.
every()
method
The every()
method checks if all elements in an array pass a particular test. It returns true
if all elements pass the test, otherwise false
:
const numbers = [10, 99, 75, 45, 33]
// check if all elements are > 15
const result = numbers.every(num => num > 15)
console.log(result) // false
The every()
method executes a function once for each element in the array. If it finds an array element for whom the function returns false
, every()
returns false
and doesn't check the remaining elements.
some()
method
The some()
method is similar to every()
except that it returns true
if one or more elements pass a specific condition:
const numbers = [10, 99, 75, 45, 33]
// check if any element > 15
const result = numbers.some(num => num > 15)
console.log(result) // true
includes()
method
The includes()
method checks if the given element exists in the array. It is similar to the some()
method. But instead of waiting for the specific condition to pass, it simply checks if the array contains the given element:
const fruits = ['Apple', 'Orange', 'Mango', 'Banana']
fruits.includes('Apple') // true
fruits.includes('Watermelon') // false
Conclusion
That's all! In this article, we looked at JavaScript arrays in detail. We learned how to create an array, access, add, update, remove its elements, and so on.
In the end, we looked at some of the most commonly used array methods. There are many more methods that you can use to manipulate an array. Check out this MDN article to learn more about them.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.