JavaScript Arrays: A Comprehensive Guide
Arrays are one of the fundamental data types in JavaScript and are essential for storing and working with lists of data. Whether you‘re a beginner or experienced JavaScript developer, having a solid grasp of how arrays work and what you can do with them is crucial. In this guide, we‘ll dive deep into JavaScript arrays and cover everything you need to know to use them effectively in your code.
What are arrays in JavaScript?
An array in JavaScript is an ordered list of values. The values can be of any type – numbers, strings, booleans, objects, or even other arrays. What makes arrays powerful is that they allow you to group related pieces of data together and perform operations across the entire collection.
Here‘s a simple example of a JavaScript array:
let fruits = [‘apple‘, ‘banana‘, ‘orange‘, ‘mango‘];
This creates an array called fruits
with four string elements. You can access individual elements using their index – the position they occupy in the array. Array indexes start at 0, so ‘apple‘
is at index 0, ‘banana‘
is at index 1, and so on.
console.log(fruits[0]); // Output: apple
console.log(fruits[2]); // Output: orange
You can also modify elements by assigning a new value at a specific index:
fruits[1] = ‘blueberry‘;
console.log(fruits); // Output: [‘apple‘, ‘blueberry‘, ‘orange‘, ‘mango‘]
Creating arrays
There are a few different ways to create arrays in JavaScript. The simplest is using array literal notation with square brackets:
let emptyArray = [];
let numbers = [1, 2, 3, 4, 5];
let mix = [1, ‘two‘, [3, 4], { five: 5 }];
You can also use the Array()
constructor, passing in the length of the array or the elements as arguments:
let a = new Array();
let b = new Array(1, 2, 3);
let c = new Array(5); // creates array of length 5 with empty slots
However, the array literal syntax is generally preferred for simplicity and readability.
Key array methods
JavaScript provides many useful built-in methods for working with arrays. Here are some of the most important ones to know:
Adding and removing elements
push()
adds one or more elements to the end of an arraypop()
removes the last element from an arrayunshift()
adds one or more elements to the beginning of an arrayshift()
removes the first element from an array
let numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers); // [1, 2, 3, 4]
numbers.pop();
console.log(numbers); // [1, 2, 3]
numbers.unshift(0);
console.log(numbers); // [0, 1, 2, 3]
numbers.shift();
console.log(numbers); // [1, 2, 3]
Slicing and splicing
slice()
extracts a section of an array and returns a new arraysplice()
removes and/or adds elements at a specific index
let numbers = [1, 2, 3, 4, 5];
let slice = numbers.slice(1, 4);
console.log(slice); // [2, 3, 4]
console.log(numbers); // [1, 2, 3, 4, 5] (original is unchanged)
numbers.splice(1, 2);
console.log(numbers); // [1, 4, 5] (removes 2 elements starting at index 1)
numbers.splice(1, 0, 2, 3);
console.log(numbers); // [1, 2, 3, 4, 5] (adds 2, 3 starting at index 1)
Searching arrays
indexOf()
returns the first index at which an element can be found, or -1 if not presentlastIndexOf()
returns the last index at which an element can be found, or -1 if not presentincludes()
determines whether an array contains a value, returning true or false
let fruits = [‘apple‘, ‘banana‘, ‘orange‘, ‘apple‘];
console.log(fruits.indexOf(‘banana‘)); // 1
console.log(fruits.indexOf(‘mango‘)); // -1
console.log(fruits.lastIndexOf(‘apple‘)); // 3
console.log(fruits.includes(‘orange‘)); // true
console.log(fruits.includes(‘grape‘)); // false
Transforming arrays
join()
concatenates all elements into a stringsplit()
divides a string into an array of substringsreverse()
reverses the order of elementssort()
sorts the elements of an array in place
let fruits = [‘apple‘, ‘banana‘, ‘orange‘];
console.log(fruits.join(‘, ‘)); // "apple, banana, orange"
let str = "apple-banana-orange";
let arr = str.split(‘-‘);
console.log(arr); // ["apple", "banana", "orange"]
fruits.reverse();
console.log(fruits); // ["orange", "banana", "apple"]
let numbers = [3, 1, 4, 1, 5, 9, 2, 6];
numbers.sort();
console.log(numbers); // [1, 1, 2, 3, 4, 5, 6, 9]
Iterating arrays
There are many ways to loop over the elements in an array. You can use a traditional for
loop:
let numbers = [1, 2, 3, 4, 5];
for(let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
Or the more concise for...of
syntax introduced in ES6:
for(let num of numbers) {
console.log(num);
}
But arrays also have several useful built-in methods for iteration:
forEach()
forEach
executes a provided function once for each array element.
numbers.forEach(num => console.log(num));
map()
map
creates a new array by calling a provided function on every element.
let squares = numbers.map(num => num * num);
console.log(squares); // [1, 4, 9, 16, 25]
reduce()
reduce
applies a function against an accumulator and each element to reduce it to a single value.
let sum = numbers.reduce((total, num) => total + num, 0);
console.log(sum); // 15
filter()
filter
creates a new array with all elements that pass a test implemented by the provided function.
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
Multi-dimensional arrays
Since arrays can contain any type of value, you can have arrays of arrays, known as multi-dimensional arrays. These are useful for representing grids or matrices.
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][1]); // 5
You can iterate over a 2D array with nested loops:
for(let row of matrix) {
for(let cell of row) {
console.log(cell);
}
}
Arrays vs Objects
Arrays and objects are the two main ways to group data in JavaScript. So when should you use one over the other?
Generally, arrays are best when you have a collection of values that are related and ordered, and you primarily need to access them by index or iterate over them. Objects are better when you have values that are related but not necessarily ordered, and you need to access them by name.
Some good use cases for arrays:
- List of products in a shopping cart
- Collection of blog posts or comments
- Rows of data from a CSV file
And for objects:
- User profile with name, email, address, etc.
- Configuration settings with key-value pairs
- Dictionary of word definitions
Best practices and pitfalls
Here are a few tips and gotchas to keep in mind when working with arrays:
-
Use
const
to declare arrays that won‘t be reassigned. But note you can still modify (mutate) the contents of aconst
array. -
Be aware that equality checks on arrays will compare references, not values:
let a = [1, 2, 3];
let b = [1, 2, 3];
console.log(a === b); // false
- Careful with off-by-one errors when accessing the last element – remember indexes start at 0!
let arr = [1, 2, 3];
console.log(arr[arr.length]); // undefined
console.log(arr[arr.length - 1]); // 3
- Many array methods mutate the original array (
push
,pop
,sort
,reverse
, etc). Useslice
first to copy if you don‘t want to modify the original:
let original = [1, 2, 3];
let copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3]
console.log(copy); // [1, 2, 3, 4]
In Summary
We‘ve covered a lot of ground in this guide to JavaScript arrays, including:
- How to create arrays and access/modify elements
- Key methods for adding, removing, slicing, splicing, searching and transforming arrays
- Iterating arrays with loops and methods like
map
,reduce
andfilter
- Multi-dimensional arrays
- When to use arrays vs objects
- Important best practices and common pitfalls
Hopefully you now have a solid foundation in using arrays effectively in your JavaScript code. Of course, there‘s always more to learn. Be sure to consult the official MDN documentation for even more details and examples. And most importantly, keep practicing and experimenting on your own!