Arrays are a fundamental component of programming in Javascript. Learning to efficiently create, manipulate and leverage the power of arrays can greatly improve your code and unlock new possibilities. In this comprehensive guide, we’ll cover everything you need to know about arrays in Javascript – from the basics through to advanced methods and techniques used by expert developers.
Whether you’re just starting out or looking to strengthen your array skills, you’ll find practical explanations and clear examples for:
- Array creation, indexing and accessing values
- Adding, removing and inserting array elements
- Iterating over arrays with for loops and forEach()
- Searching arrays with indexOf() and includes()
- Sorting arrays with sort() and custom sorts
- Manipulating arrays with methods like push(), pop(), shift(), unshift()
- Using map(), filter() and reduce() for power array operations
- Multidimensional arrays and array destructuring
- And much more!
Let’s dive in and conquer arrays in Javascript!
Array Creation and Indexing
To create an array in Javascript, you simply declare it with square brackets [] and separate elements with commas:
let fruits = ['Apple', 'Banana', 'Orange'];
This creates an array with three elements. An array element can be any Javascript data type - strings, numbers, booleans, objects, or even another array.
You can access individual elements in an array using their index. Array indexes start counting from 0:
let firstFruit = fruits[0]; // Apple
To get the last element, you use the length property minus 1:
let lastFruit = fruits[fruits.length - 1]; // Orange
This array indexing syntax is the fundamental way to retrieve and modify array elements in Javascript.
Adding and Removing Array Elements
There are a couple easy ways to add elements to the end of an array:
push()
The push() method appends one or more elements to the end:
fruits.push('Strawberry');
console.log(fruits); // ['Apple', 'Banana', 'Orange', 'Strawberry']
concat()
Concatenates another array or values to create a new array:
let moreFruits = fruits.concat(['Strawberry', 'Blueberry']);
console.log(moreFruits); // ['Apple', 'Banana', 'Orange', 'Strawberry', 'Blueberry']
To remove the last element, you can use pop():
fruits.pop(); // Removes Strawberry
And to remove the first element, use shift():
fruits.shift(); // Removes Apple
splice()
For inserting or removing elements anywhere in the array, splice() is more flexible. The first 2 parameters are the start index and number of elements to remove. Then you can pass additional elements to insert:
// Remove 1 element at index 1
fruits.splice(1, 1); // Removes Banana
// Insert two elements at index 1
fruits.splice(1, 0, 'Lemon', 'Kiwi');
splice() is powerful for modifying arrays dynamically.
slice()
The slice() method returns a slice of the array starting at the provided start index and ending before the end index:
let arr = [1, 2, 3, 4, 5];
arr.slice(1, 3); // [2, 3]
Slice is useful for getting parts of arrays.
Iterating Over Arrays
Looping through array elements is an extremely common task. There are a few ways to iterate over an array in Javascript:
for Loop
The basic for loop allows you to loop over elements by index:
for(let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
This loops through and logs each element in fruits.
for...of Loop
The for...of loop iterates directly over the array values:
for(let fruit of fruits) {
console.log(fruit);
}
This makes the code simpler by removing the need to use indexes.
forEach()
The forEach() method calls a callback function on each element:
fruits.forEach(function(fruit) {
console.log(fruit)
});
You get the direct element like for...of, but without having to set up a loop.
forEach() is clean and concise way to iterate that works great in many cases.
All three styles have their uses. Mastering iterating is vital for efficiency working with arrays.
Searching Arrays
You'll often need to search for the presence of a value in an array. There are built-in methods that make this quick and easy:
indexOf()
Returns the index of a value, or -1 if not found:
let index = fruits.indexOf('Banana'); // 2
indexOf() starts searching from the beginning. Use lastIndexOf() to search from the end.
includes()
Returns a boolean indicating if the value exists:
let hasOrange = fruits.includes('Orange'); // true
includes() is often preferable over indexOf() since you just care about existence, not the index.
Sorting Arrays
Sorting arrays puts the elements in ascending or descending order:
let scores = [10, 5, 20, 15, 1];
scores.sort(); // [1, 5, 10, 15, 20]
By default sort() converts elements to strings and sorts alphabetically.
To sort numbers numerically, pass a compare function:
scores.sort((a, b) => a - b); // [1, 5, 10, 15, 20]
For descending order, subtract b from a:
scores.sort((a, b) => b - a); // [20, 15, 10, 5, 1]
There are more advanced sorting techniques like .localeCompare() for strings, but this covers the basic approach.
Array Mapping and Filtering
Two very useful array methods are map() and filter().
map()
Map iterates over an array, transforming each element via a callback function:
let prices = [5, 10, 15, 20];
let newPrices = prices.map(price => price * .85);
console.log(newPrices); // [4.25, 8.5, 12.75, 17]
This maps each price to a new discounted price. Map is ideal for transformations.
filter()
Filter also iterates over arrays, but returns a new array with only elements that pass a conditional:
let bigNumbers = [1, 5, 10, 20];
let smallNums = bigNumbers.filter(num => num < 5);
console.log(smallNums); // [1]
Filter is perfect for filtering out unwanted values.
Map and filter open up a world of possibilities for manipulating array data.
Array Destructuring
Destructuring is a convenient way to extract multiple values from arrays:
let [first, second] = ['Apple', 'Banana'];
console.log(first); // Apple
console.log(second); // Banana
You can destructure any values you need:
let [fruits, vegetables] = ['Strawberry', 'Carrot'];
let [first, ,third] = ['Apple', 'Orange', 'Banana'];
Destructuring makes extracting array values simpler.
Multidimensional Arrays
Arrays can contain other arrays to create multidimensional or nested arrays:
let matrix = [
[1, 2, 3],
[4, 5, 6]
];
You use multiple indexes to access nested elements:
let six = matrix[1][2]; // 6
Methods like map(), filter() and reduce() work on inner arrays to efficiently process multidimensional data.
Multidimensional arrays are perfect for grid-based data.
Reducing Arrays
The reduce() method runs a reducer callback on each element to produce a single value:
let numbers = [1, 2, 3, 4];
let sum = numbers.reduce((total, num) => total + num, 0); // 10
This sums all the numbers, with 0 as the initial total. Reduce is great for boiling arrays down to a single result.
Checking All Array Elements
You can see if all or some values in an array pass a test using every() and some():
let examScores = [90, 75, 96];
let passed = examScores.every(score => score >= 70); // true
every() returns true only if all elements pass.
let passed = examScores.some(score => score >= 90); // true
some() returns true if any of the elements pass the test.
Finding Array Min and Max
To find minimum and maximum values in an array, use Math.min() and Math.max():
let ages = [32, 33, 16, 40];
Math.min(...ages); // 16
Math.max(...ages); // 40
The ... spread operator spreads the array into arguments.
Array-Like Objects
Some objects like NodeList may look like arrays. Convert them using Array.from():
let divs = document.querySelectorAll('div'); // NodeList
divs = Array.from(divs); // Now an array
This allows array methods to work on array-like objects.
Array Methods with thisArg
Many array methods like forEach(), map(), filter(), etc. accept a thisArg as the last argument. This sets the this value inside the callback:
let user = {
name: 'John',
printName: function(num) {
console.log(this.name);
}
}
[1,2,3].forEach(user.printName, user);
// Logs 'John' 3 times
By passing user as thisArg, we set this to the user object inside printName().
Flattening Multidimensional Arrays
You can flatten nested arrays using reduce() and concat():
let matrix = [[1,2], [3,4], [5,6]];
let flat = matrix.reduce((acc, cur) => acc.concat(cur), []);
// [1,2,3,4,5,6]
The concat() joins the flattened output array acc with the current inner array cur.
Unique Values
To get an array of unique values, create a Set and spread it back to an array:
let dupes = [1, 2, 2, 3, 3, 3];
let unique = [...new Set(dupes)]; // [1, 2, 3]
Sets only allow unique values, removing duplicates.
Array.fill()
The fill() method lets you fill all elements of an array with a static value:
let lengths = new Array(3).fill(10);
// [10, 10, 10]
This creates an array of 3 elements filled with 10.
Array.from()
Array.from() lets you create a new array from an array-like object:
let divs = document.querySelectorAll('div');
let array = Array.from(divs);
This gives you full array capabilities on a NodeList or other array-like object.
Array.isArray()
Use Array.isArray() to check if an object is an array:
let arr = [1, 2, 3];
Array.isArray(arr); // true
This is better than using instanceof because it works across iframes.
Array Buffers
Array buffers represent fixed-length raw binary data. To manipulate, convert to a typed array:
let buffer = new ArrayBuffer(12);
let view = new Uint8Array(buffer);
view[0] = 5;
Buffers are useful for low-level operations.
Array Iteration Shorthands
There are some shorthand iteration methods like every(), some() and find():
let ages = [32, 15, 20];
// Check if all >= 18
ages.every(age => age >= 18);
// Check if some >= 18
ages.some(age => age >= 18);
// Get first >= 18
ages.find(age => age >= 18);
These can make conditionally checking arrays concise.
Best Practices for Working with Arrays
When working with arrays in Javascript, following some key best practices can help you write optimized, clean code and avoid common mistakes.
Initialize to a Specific Size
If you know the number of elements your array will hold, initialize it with that size:
// Initialize with room for 10 elements
let list = new Array(10);
This allocates the array storage upfront rather than incrementally growing it as you add items.
Avoid Side Effects
Map allows transforming arrays without mutations:
// Bad - mutates original array
let prices = [10, 20, 30];
for (let i = 0; i < prices.length; i++) {
prices[i] *= 0.5;
}
// Good - returns a new array
let salePrices = prices.map(price => price * 0.5);
This avoids potential bugs from changing the original.
Copy Arrays to Avoid Reference Issues
Arrays are assigned by reference, so copying requires creation of new instance:
// Bad - arr2 is just a reference to arr1
let arr1 = [1,2,3];
let arr2 = arr1;
// Good - creates separate copy
let arr1 = [1,2,3];
let arr2 = [...arr1];
Check Length to Avoid Out of Bounds
Check the length in loops to prevent errors:
let items = [1,2,3];
// Bad - could exceed length if changed
for (let i = 0; i < 10; i++) {
console.log(items[i]);
}
// Good - respects current length
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
}
Prefer for...of Loops
The for...of loop clearly expresses iterating over array values:
let colors = ['red', 'green', 'blue'];
// Unclear with index access
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
// Clearer with for...of
for (let color of colors) {
console.log(color);
}
Use Array Methods for Readability
Array methods like filter(), map(), reduce() etc. make code more readable than loops:
let numbers = [1, 2, 3, 4];
// Unclear with for loop
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
// Clear intent with reduce()
let sum = numbers.reduce((prev, curr) => prev + curr, 0);
Method chaining also expresses the logical flow:
let filtered = numbers
.filter(n => n > 2)
.map(n => n * 2);
Destructure Concisely
Array destructuring cleanly extracts values from arrays:
// Verbose variable assignments
let colors = ['red', 'green', 'blue'];
let red = colors[0];
let green = colors[1];
let blue = colors[2];
// Simpler destructuring
let [red, green, blue] = colors;
Check Array Type
Use Array.isArray() for best practice type checking:
let arr = [1, 2, 3];
// Avoid typeof
typeof arr === 'object'
// Use Array.isArray()
Array.isArray(arr);
Handle Sparse Arrays Carefully
Sparse arrays contain "holes" where elements are undefined:
let sparse = [1,,3];
sparse.length; // 3
sparse[1]; // undefined
Check for holes before accessing elements to avoid bugs.
Set Array Lengths Sparingly
Manually setting array length can create sparse arrays:
let arr = [1,2,3];
arr.length = 5; // [1,2,3, , ]
It's better to use methods like push(), splice() to insert elements.
Avoid Excessive Array Copying
Copying arrays like arr2 = [...arr1] has a performance cost. Avoid unnecessary copying:
// Unneeded copying with each iteration
for (let i = 0; i < list.length; i++) {
let arr = [...list];
// ...
}
// Reference original array instead
for (let i = 0; i < list.length; i++) {
let arr = list;
// ...
}
Avoid Reverse() for Performance
The reverse() method is relatively slow. Consider iterating the array instead.
Conclusion: Key Takeaways for Working with Arrays
Arrays are a critical tool for managing collections of data in Javascript. Mastering arrays will make your code simpler and more efficient.
Here are the key lessons for working with arrays:
- Use [] and , to create arrays with any values like strings, numbers, objects, or other arrays inside.
- Access array elements with
array[index]
. The index starts at 0 for the first element. - Add and remove elements using
push()
,pop()
,shift()
,unshift()
andsplice()
. - Loop over arrays with a for loop, for...of loop or the forEach() method.
- Search for array values using
indexOf()
to find the index orincludes()
to get a boolean if it exists. - Sort arrays into ascending or descending order using
sort()
. - Pass a compare function for custom sorting.
- Transform arrays by mapping values to new elements and filtering out unwanted ones.
- Use array destructuring like
let [x, y] = [1, 2]
to neatly assign values. - Create multidimensional arrays like
[[1, 2], [3, 4]]
for grids of data. - Check array length when looping over arrays to avoid going out of bounds.
- Copy arrays and use array methods to avoid mutating the original.
I hope these array tips help you use arrays like a pro! Let me know if you have any other array questions.
If you like my post, please follow me on JSDevJournal
Top comments (0)