We encounter arrays every day as developers and it is an indispensable part of programming. But the problem with most beginners is they have a hard time understanding and using JavaScript Arrays.
A good understanding of JavaScript arrays is important if you want to become a better JS developer. You will learn everything about JavaScript arrays and practical solutions for common problems in this article.
JavaScript Arrays – The Basics
An array is just a linear collection of values (called array elements). Therefore, with arrays, you can store different values in a single variable. Here is an example to create arrays in JavaScript:
// an array of numbers const numbers = [3, 4, 6, 10] // an array of names const names = ['john', 'peter', 'alex'] // an array with mixed values const values = [5, 'morning', false, 33]
We specify the array elements inside the square brackets and they are separated by commas. Arrays in JavaScript can contain any possible types in JavaScript.
You can create an array of strings, numbers, booleans, objects, or even an array of arrays (known as nested arrays). Also, you can store different/mixed types of values in a single array unlike statically typed languages like C++.
Accessing Properties of JavaScript Arrays
We can access the elements of an array using an index. Every array element has an index or position. The first element of the array is at index 0, the next element is at index 1, and so on.
So, to access an array element, we specify the index inside square brackets after the array name.
numbers[2] // 6 names[1] // peter values[0] // 5 values[9] // undefined
Also, trying to access an array element that does not exist will return undefined.
If you create an array of objects, then the same rules for arrays and objects apply. First, you get the object, and then use the dot notation to access the object properties.
// an array of users - each element is an object const users = [ { name: 'john', email: 'john@gmail.com', }, { name: 'john', email: 'john@gmail.com', }, ] // get the email address of the first user console.log(users[0].email)
JavaScript Arrays are ‘Reference Type’ values
When you create an array and store it in a variable, then the reference to the array is stored. Thus, the actual value of the array is not stored in a variable. This means that you cannot copy an array simply by reassigning the array variable to a new one.
When you pass an array to a function, the same thing happens. The array reference is passed. So if you do any modifications (called mutations) to the array then it is going to affect the original array.
const planets = ['mercury', 'venus', 'earth'] const planets2 = planets // planets and planets2 have the same reference to array in memory planets2[0] = 'jupiter' // changing planets2 changes planets array too. console.log(planets[0]) // jupiter
Common operations on JavaScript arrays
Once you start working with arrays, you need to perform many different operations depending on the requirement. So operations like updating an array, removing an element, etc are very common.
1. Adding/removing elements from an array
You can use pop() and push() to remove and add elements from the end of an array. And to remove and insert elements from the beginning of the array, use shift() and unshift() respectively.
const planets = ['mercury', 'venus', 'earth'] planets.pop() console.log(planets) // [ 'mercury', 'venus' ] planets.push('jupiter') console.log(planets) // [ 'mercury', 'venus', 'jupiter' ] planets.shift() console.log(planets) // [ 'venus', 'jupiter' ] planets.unshift('saturn') console.log(planets) // [ 'saturn', 'venus', 'jupiter' ]
You can also use the ES6 equivalent of push/unshift.
let planets = ['mercury', 'venus', 'earth'] planets = [...planets, 'jupiter'] // or add at beginning // planets = ['jupiter', ...planets] console.log(planets) // [ 'mercury', 'venus', 'earth', 'jupiter' ]
However, using the ES6 spread technique does not modify the original array, it instead creates a new copy of the array with the new elements added at the last or the beginning if any.
2. Looping through an array
We can use all the standard C loops like for, while, and do-while in JavaScript to loop through arrays.
However, in addition to that, there are three more loops to make working with arrays easier that you should prefer instead:
forEach()
This method takes a callback function that receives two parameters: element and index. It loops through every element in the array.
let planets = ['mercury', 'venus', 'earth'] planets.forEach(function (element, index) { console.log(index, element) }) /* 0 mercury 1 venus 2 earth */
map()
The map() method works the same as forEach but it has an additional feature to return a value every loop. The map() method returns a new array while forEach does not return anything.
for… of loop
Using for… of, you can loop through the array elements. But unlike the map() and forEach() methods, for…of is not a method. It is a loop construct of JavaScript just like while and for.
let planets = ['mercury', 'venus', 'earth'] for (let planet of planets) { console.log(planet) } /* 0 mercury 1 venus 2 earth */
3. Length of an array
You can use the length property of an array to find the total elements of an array. This is useful for getting the last element of an array and in iterating for and while loops.
let planets = ['mercury', 'venus', 'earth', 'neptune'] const lastPlanet = planets[planets.length - 1] console.log(lastPlanet) // neptune
Useful JavaScript Array Methods
indexOf(arrayValue)
Returns the index of an array element. But it returns -1 if the element is not found. Use lastIndexOf() to start searching from the end of the array. It is useful when there are two or more duplicate array elements.
let planets = ['mercury', 'venus', 'earth', 'neptune'] console.log(planets.indexOf('earth')) // 2 console.log(planets.indexOf('pluto')) // -1
join(delimeter)
Converts an array to a string by joining all the elements of an array with the specified delimiter.
let planets = ['mercury', 'venus', 'earth', 'neptune'] console.log(planets.join(' | ')) // mercury | venus | earth | neptune
concat(array1, array2, …)
Combine two or more arrays. It returns a new copy of the combined arrays.
let planets = ['mercury', 'venus', 'earth', 'neptune'] let innerPlanets = ['mercury', 'venus', 'earth', 'mars'] let outerPlanets = ['jupiter', 'saturn', 'uranus', 'neptune'] const allPlanets = innerPlanets.concat(outerPlanets) console.log(allPlanets) // [ 'mercury', 'venus', 'earth', 'mars', 'jupiter', 'saturn', // 'uranus', 'neptune']
slice(start, end)
Returns a part of an array from the start index(inclusive) to the end index(exclusive).
const planets = [ 'mercury','venus','earth','mars', 'jupiter','saturn','uranus','neptune', ] // end index 7 is exclusive, // so the 7th array element is not returned const outerPlanets = planets.slice(4, 7) console.log(outerPlanets) // [ 'jupiter', 'saturn', 'uranus' ]
splice(start, length, [elem1, elem2,…])
Removes a part of an array from the start index to the specified length. It takes an optional parameter to replace it with new elements.
const planets = [ 'mercury','venus','earth','mars', 'jupiter','saturn','uranus','neptune', ] // arguments: startIndex, length, replacement console.log(planets.splice(1, 4, 'new planet 1', 'new planet 2')) // returns removed elements [ 'venus', 'earth', 'mars', 'jupiter' ] console.log(planets) // splice() method mutates the original array // ['mercury','new planet 1','new planet 2','saturn', // 'uranus','neptune']
There are many more array methods provided by JavaScript which developers power to using and manipulating arrays. Knowing and having these methods in your tool belt is a great advantage.
Solving common array problems
Array problems arise many times when developing backend or frontend applications with JavaScript. So, here are some solutions to common array problems that you can use to overcome it easily.
1. Insert an element at a specific index
Using splice we can insert an element at a specific index if we put the second argument as 0.
array.splice(indexToInsert, 0, elementToInsert)
2. Remove element from a specific index
Use splice to remove an element by specifying the length as 1.
array.splice(indexToRemove, 1)
3. Shuffle a JavaScript Arrays
Using sort() and Math.random() can randomize an array in just a line of code. However, it is not recommended to use this technique for large arrays.
array.sort( () => .5 - Math.random() );
4. Find an element of an array.
You can use the inbuilt find() method to return the element that matches your condition.
const users = [ { name: 'john', email: 'john@gmail' }, { name: 'david', email: 'david@gmail.com' }, { name: 'gloria', email: 'gloria@gmail.com' }, ] // find the array element with the given condition const user = users.find(e => e.name === 'david') // const userIndex = users.findIndex(e => e.name === 'david') console.log(user) // { name: 'david', email: 'david@gmail.com' }
5. Filter an array
You can filter out the array elements using the inbuilt filter() method.
const users = [ { name: 'john', gender: 'male' }, { name: 'david', gender: 'male' }, { name: 'gloria', gender: 'female' }, ] // filter the array element with the given condition const maleUsers = users.filter(e => e.gender === 'male') console.log(maleUsers) /* [ { name: 'john', gender: 'male' }, { name: 'david', gender: 'male' } ] */
6. Clone an array
You can create a new copy of an array using slice() or ES6 spread syntax.
const names = ['david', 'jane'] // clone by slicing console.log(names.slice()) // ['david', 'jane'] // clone by using spread syntax es6 console.log([...names]) // ['david', 'jane']
Conclusion
The advantage that JavaScript arrays have is the huge number of inbuilt methods available to the developer. So, in this guide, we have explained arrays and covered many useful methods.
There are many more advanced methods and related array concepts that you should learn. The key to remembering them is constantly using and integrating these techniques in your JavaScript code.