JavaScript Arrays: A Detailed and Comprehensive Guide

Like tidy shelves storing diverse treasures, JavaScript arrays organize sequences of data with order and efficiency. This comprehensive guide unravels their secrets, equipping you to master array creation, access, and manipulation in your code.

Table of Contents

What is an array?

An array is a data structure that can store multiple values of the same or different types in a single variable. Arrays are useful for storing and manipulating lists of data, such as numbers, strings, objects, and even other arrays.

How to create an array?

There are two main ways to create an array in JavaScript: using an array literal or using the Array constructor function.

Using an array literal

An array literal is a comma-separated list of values, enclosed by square brackets. For example:

Javascript
                        
// Create an array literal
const fruits = ["apple", "banana", "orange"];

An array literal is the simplest and most common way to create an array in JavaScript. It is also a good practice to use the const keyword to declare arrays, unless you need to reassign the variable to a different value later. Learn more about const with arrays in the chapter: JS Array Const.

Using the Array constructor function

The Array constructor function is a built-in function that creates and returns a new array object. You can use the new keyword, followed by the name of the function and any arguments. For example:

Javascript
                        
// Create an array using the Array constructor function
const numbers = new Array(1, 2, 3, 4, 5);

The Array constructor function can also take a single argument that specifies the length of the array, without providing any values. For example:

Javascript
                        
// Create an empty array with a length of 10
const empty = new Array(10);

The Array constructor function is less concise and less readable than the array literal method, and it can also cause some confusion when passing a single argument. Therefore, it is recommended to use the array literal method whenever possible.

How to access and modify array elements?

You can access and modify array elements using their index, which is a zero-based number that represents the position of the element in the array. You can use either dot notation or bracket notation to access the index property of the array. For example:

Javascript
                        
// Access and modify array elements using dot notation
fruits[0] = "pear"; // Modify the first element
console.log(numbers[3]); // Access the fourth element
console.log(empty[5]); // Access the sixth element

// Access and modify array elements using bracket notation
fruits[1] = "mango"; // Modify the second element
console.log(numbers[2]); // Access the third element
console.log(empty[9]); // Access the tenth element

Note that you can access and modify any element in the array, even if it is beyond the current length of the array. This will create undefined elements in the array, which can cause unexpected results. For example:

Javascript
                        
// Access and modify array elements beyond the current length
fruits[5] = "kiwi"; // Modify the sixth element
console.log(fruits); // ["pear", "mango", "orange", undefined, undefined, "kiwi"]
console.log(fruits[4]); // undefined

How to use array methods and properties?

Arrays have many built-in methods and properties that allow you to perform various operations on them, such as adding, removing, sorting, searching, slicing, and looping through array elements. Some of the most common and useful array methods and properties are:

length

The length property returns the number of elements in the array. It can also be used to set the length of the array, by assigning a new value to it. For example:

Javascript
                        
// Use the length property to get and set the length of the array
console.log(fruits.length); // 6
fruits.length = 3; // Set the length to 3
console.log(fruits); // ["pear", "mango", "orange"]

push() and pop()

The push() method adds one or more elements to the end of the array, and returns the new length of the array. The pop() method removes the last element from the array, and returns the removed element. For example:

Javascript
                        
// Use the push() and pop() methods to add and remove elements from the end of the array
numbers.push(6, 7, 8); // Add 6, 7, and 8 to the end of the array
console.log(numbers); // [1, 2, 3, 4, 5, 6, 7, 8]
numbers.pop(); // Remove the last element from the array
console.log(numbers); // [1, 2, 3, 4, 5, 6, 7]

unshift() and shift()

The unshift() method adds one or more elements to the beginning of the array, and returns the new length of the array. The shift() method removes the first element from the array, and returns the removed element. For example:

Javascript
                        
// Use the unshift() and shift() methods to add and remove elements from the beginning of the array
numbers.unshift(0, -1, -2); // Add 0, -1, and -2 to the beginning of the array
console.log(numbers); // [0, -1, -2, 1, 2, 3, 4, 5, 6, 7]
numbers.shift(); // Remove the first element from the array
console.log(numbers); // [-1, -2, 1, 2, 3, 4, 5, 6, 7]

concat()

The concat() method creates and returns a new array that contains the elements of the original array and the elements of one or more arrays or values passed as arguments. The original array is not modified. For example:

Javascript
                        
// Use the concat() method to create a new array that contains the elements of two or more arrays
const letters = ["a", "b", "c"];
const numbersAndLetters = numbers.concat(letters); // Create a new array that contains the elements of numbers and letters
console.log(numbersAndLetters); // [-1, -2, 1, 2, 3, 4, 5, 6, 7, "a", "b", "c"]
console.log(numbers); // [-1, -2, 1, 2, 3, 4, 5, 6, 7]
console.log(letters); // ["a", "b", "c"]

slice()

The slice() method creates and returns a new array that contains a shallow copy of a portion of the original array, specified by the start and end arguments. The original array is not modified. The start argument is the index of the first element to include in the new array, and the end argument is the index of the first element to exclude from the new array. If the start argument is omitted, it defaults to 0. If the end argument is omitted, it defaults to the length of the array. For example:

Javascript
                        
// Use the slice() method to create a new array that contains a portion of the original array
const numbersCopy = numbers.slice(); // Create a new array that contains a copy of the entire array
console.log(numbersCopy); // [-1, -2, 1, 2, 3, 4, 5, 6, 7]
const numbersPart = numbers.slice(2, 5); // Create a new array that contains a portion of the array from index 2 to index 5 (not including 5)
console.log(numbersPart); // [1, 2, 3]
console.log(numbers); // [-1, -2, 1, 2, 3, 4, 5, 6, 7]

splice()

The splice() method modifies the original array by adding, removing, or replacing elements, and returns an array that contains the deleted elements. The splice() method takes three or more arguments: the start argument is the index at which to start the modification, the deleteCount argument is the number of elements to delete from the start index, and the rest of the arguments are the elements to add to the array, starting from the start index. If the deleteCount argument is omitted, it defaults to the length of the array from the start index. For example:

Javascript
                        
// Use the splice() method to modify the original array by adding, removing, or replacing elements
numbers.splice(2, 3, 10, 20, 30); // Modify the array by deleting 3 elements from index 2, and adding 10, 20, and 30 to the same index
console.log(numbers); // [-1, -2, 10, 20, 30, 4, 5, 6, 7]
numbers.splice(6); // Modify the array by deleting all elements from index 6 to the end
console.log(numbers); // [-1, -2, 10, 20, 30, 4]

sort()

The sort() method sorts the elements of the array in place, and returns the sorted array. By default, the sort() method converts the elements to strings and compares them in lexicographical order. This may produce unexpected results for arrays that contain numbers or mixed types. To sort the array according to a custom order, you can provide a compare function as an argument to the sort() method. The compare function takes two parameters, a and b, and returns a negative value if a should come before b, a positive value if a should come after b, or zero if a and b are equal. For example:

Javascript
                        
// Use the sort() method to sort the elements of the array
letters.sort(); // Sort the letters array in ascending lexicographical order
console.log(letters); // ["a", "b", "c"]
numbers.sort(); // Sort the numbers array in ascending lexicographical order
console.log(numbers); // [-1, -2, 10, 20, 30, 4]
numbers.sort(function(a, b) {
return a - b;
}); // Sort the numbers array in ascending numerical order, using a compare function
console.log(numbers); // [-2, -1, 4, 10, 20, 30]

reverse()

The reverse() method reverses the order of the elements in the array in place, and returns the reversed array. For example:

Javascript
                        
// Use the reverse() method to reverse the order of the elements in the array
letters.reverse(); // Reverse the order of the letters array
console.log(letters); // ["c", "b", "a"]
numbers.reverse(); // Reverse the order of the numbers array
console.log(numbers); // [30, 20, 10, 4, -1, -2]

join()

The join() method creates and returns a new string that concatenates all the elements of the array, separated by a specified separator. The original array is not modified. If the separator argument is omitted, it defaults to a comma. For example:

Javascript
                        
// Use the join() method to create a new string that concatenates all the elements of the array
const fruitsString = fruits.join(); // Create a new string that concatenates all the elements of the fruits array, separated by a comma
console.log(fruitsString); // "pear,mango,orange"
const numbersString = numbers.join(" "); // Create a new string that concatenates all the elements of the numbers array, separated by a space
console.log(numbersString); // "30 20 10 4 -1 -2"

indexOf() and lastIndexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if the element is not present. The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if the element is not present. You can also provide a second argument to specify the index from which to start the search. For example:

Javascript
                        
// Use the indexOf() and lastIndexOf() methods to find the index of a given element in the array
console.log(fruits.indexOf("orange")); // 2
console.log(fruits.indexOf("apple")); // -1
console.log(fruits.lastIndexOf("orange")); // 2
console.log(fruits.lastIndexOf("apple")); // -1
console.log(numbers.indexOf(10)); // 2
console.log(numbers.indexOf(10, 3)); // -1
console.log(numbers.lastIndexOf(10)); // 2
console.log(numbers.lastIndexOf(10, 1)); // -1

includes()

The includes() method determines whether an array includes a certain value among its elements, and returns a boolean value. You can also provide a second argument to specify the index from which to start the search. For example:

Javascript
                        
// Use the includes() method to determine whether an array includes a certain value among its elements
console.log(fruits.includes("orange")); // true
console.log(fruits.includes("apple")); // false
console.log(numbers.includes(10)); // true
console.log(numbers.includes(10, 3)); // false

find() and findIndex()

The find() method returns the value of the first element in the array that satisfies a given testing function, or undefined if no element satisfies the function. The findIndex() method returns the index of the first element in the array that satisfies a given testing function, or -1 if no element satisfies the function. The testing function takes one parameter, which is the current element being processed in the array. For example:

Javascript
                        
// Use the find() and findIndex() methods to find the value or index of the first element that satisfies a given testing function
const odd = numbers.find(function(element) {
  return element % 2 !== 0;
}); // Find the value of the first odd element in the numbers array
console.log(odd); // -1
const oddIndex = numbers.findIndex(function(element) {
  return element % 2 !== 0;
}); // Find the index of the first odd element in the numbers array
console.log(oddIndex); // 4

filter()

The filter() method creates and returns a new array that contains all the elements of the original array that pass a given testing function. The original array is not modified. The testing function takes one parameter, which is the current element being processed in the array. For example:

Javascript
                        
// Use the filter() method to create a new array that contains all the elements that pass a given testing function
const even = numbers.filter(function(element) {
  return element % 2 === 0;
}); // Create a new array that contains all the even elements in the numbers array
console.log(even); // [30, 20, 10, 4]
const vowels = letters.filter(function(element) {
  return ["a", "e", "i", "o", "u"].includes(element);
}); // Create a new array that contains all the vowels in the letters array
console.log(vowels); // ["a"]

map()

The map() method creates and returns a new array that contains the results of calling a given function on every element of the original array. The original array is not modified. The function takes one parameter, which is the current element being processed in the array. For example:

Javascript
                        
// Use the map() method to create a new array that contains the results of calling a given function on every element of the original array
const squares = numbers.map(function(element) {
  return element * element;
}); // Create a new array that contains the squares of the elements in the numbers array
console.log(squares); // [900, 400, 100, 16, 1, 4]
const upperCase = letters.map(function(element) {
  return element.toUpperCase();
}); // Create a new array that contains the upper case versions of the elements in the letters array
console.log(upperCase); // ["C", "B", "A"]

reduce() and reduceRight()

The reduce() method applies a given function to each element of the array, from left to right, and accumulates the result in a single value. The reduceRight() method does the same, but from right to left. The function takes two parameters, which are the accumulator and the current element being processed in the array. You can also provide a second argument to the reduce() or reduceRight() method, which is the initial value of the accumulator. For example:

Javascript
                        
// Use the reduce() and reduceRight() methods to apply a given function to each element of the array and accumulate the result in a single value
const sum = numbers.reduce(function(accumulator, element) {
  return accumulator + element;
}, 0); // Calculate the sum of the elements in the numbers array, starting from 0
console.log(sum); // 61
const product = numbers.reduceRight(function(accumulator, element) {
  return accumulator * element;
}, 1); // Calculate the product of the elements in the numbers array, starting from 1
console.log(product); // -4800

forEach()

The forEach() method executes a given function for each element of the array. The function takes one parameter, which is the current element being processed in the array. The forEach() method does not return any value, and does not modify the original array. It is mainly used for performing side effects, such as logging or updating the user interface. For example:

Javascript
                        
// Use the forEach() method to execute a given function for each element of the array
fruits.forEach(function(element) {
  console.log("I like " + element);
}); // Log a message for each element in the fruits array
// I like pear
// I like mango
// I like orange

How to loop through array elements?

There are different ways to loop through array elements in JavaScript, such as using a for loop, a for...of loop, a for...in loop, or a while loop. However, some of these methods have some drawbacks or limitations, such as:

  • A for loop requires you to keep track of the index and the length of the array, and it can be prone to off-by-one errors.
  • A for...of loop can loop through the values of the array, but not the indexes, and it can also loop through other iterable objects, such as strings or maps, which may not be desirable.
  • A for...in loop can loop through the indexes of the array, but not the values, and it can also loop through the enumerable properties of the array object, such as length or prototype, which may not be desirable.
  • A while loop requires you to keep track of the index and the condition, and it can be prone to infinite loops.

Therefore, a better way to loop through array elements in JavaScript is to use the array methods that we have learned in the previous section, such as forEach(), map(), filter(), reduce(), etc. These methods are more concise, readable, and functional, and they avoid the pitfalls of the other methods. For example:

Javascript
                        
// Loop through array elements using array methods
fruits.forEach(function(element, index) {
  console.log("The element at index " + index + " is " + element);
}); // Log the element and the index for each element in the fruits array
// The element at index 0 is pear
// The element at index 1 is mango
// The element at index 2 is orange

const doubled = numbers.map(function(element) {
  return element * 2;
}); // Create a new array that contains the doubled values of the elements in the numbers array
console.log(doubled); // [60, 40, 20, 8, -2, -4]
const positive = numbers.filter(function(element) {
  return element > 0;
}); // Create a new array that contains only the positive elements in the numbers array
console.log(positive); // [30, 20, 10, 4]
const sum = numbers.reduce(function(accumulator, element) {
  return accumulator + element;
}); // Calculate the sum of the elements in the numbers array
console.log(sum); // 61

How to differentiate between arrays and array-like objects?

An array-like object is an object that has a length property and indexed properties, but does not have the array methods or the prototype of an array. For example, the arguments object, which is available inside every function, is an array-like object. It has a length property that indicates the number of arguments passed to the function, and it has indexed properties that correspond to the argument values. However, it does not have the array methods, such as push(), pop(), or slice(), and it does not inherit from the Array.prototype object. For example:

Javascript
                        
// Use the arguments object, which is an array-like object
function sum() {
  console.log(arguments); // {0: 1, 1: 2, 2: 3, length: 3}
  console.log(arguments.length); // 3
  console.log(arguments[0]); // 1
  console.log(arguments.push(4)); // TypeError: arguments.push is not a function
  console.log(arguments instanceof Array); // false
}

sum(1, 2, 3); // Call the sum function with three arguments

To differentiate between arrays and array-like objects, you can use the instanceof operator, which checks if an object is an instance of a constructor function, and returns a boolean value. For example, you can check if an object is an instance of the Array constructor function, and if it returns true, then the object is an array. For example:

Javascript
                        
// Use the instanceof operator to differentiate between arrays and array-like objects
console.log(fruits instanceof Array); // true
console.log(numbers instanceof Array); // true
console.log(letters instanceof Array); // true
console.log(arguments instanceof Array); // false

Another way to differentiate between arrays and array-like objects is to use the Array.isArray() method, which checks if a value is an array, and returns a boolean value. For example:

Javascript
                        
// Use the Array.isArray() method to differentiate between arrays and array-like objects
console.log(Array.isArray(fruits)); // true
console.log(Array.isArray(numbers)); // true
console.log(Array.isArray(letters)); // true
console.log(Array.isArray(arguments)); // false

Conclusion

In this article, we have learned how to create and manipulate arrays in JavaScript, using array literals, methods, and properties. We have also learned how to differentiate between arrays and array-like objects, using the instanceof operator or the Array.isArray() method. Arrays are one of the most important and useful data structures in JavaScript, and they can help you store and process lists of data in a simple and efficient way.