Arrays are one of the fundamental data structures in JavaScript. They allow you to store and organize multiple values under a single variable. Understanding arrays is crucial for building robust and efficient JavaScript applications. This article explores the fundamentals of JavaScript arrays, covering everything you need to know to master their usage.
What is an Array?
An array is a collection of elements that can be stored under a single variable. Each element in an array is assigned an index starting from zero. Arrays in JavaScript are dynamic, meaning they can be resized and modified during runtime.
Creating Arrays
To create an array, you can use the array literal notation [] or the Array constructor function. Here’s an example:
// Empty array
let emptyArray = [];
// Array with initial values
let languages = ['C', 'Dart', 'JavaScript', 'Kotlin', 'Swift'];
// Using the Array constructor
let numbers = new Array(1, 2, 3, 4, 5);
Accessing Array Elements
You can access array elements by their index using square brackets [] notation. Array indices start from 0. Here’s an example:
let numbers = [1, 2, 3, 4, 5];
// Access the element at index 0
let fst = numbers[0]
// Access the element at index 4
let lst = numbers[4]
// Print the elements to the console
console.log(`The element at index 0 is ${fst}`);
console.log(`The element at index 4 is ${lst}`);
Modifying Array Elements
Arrays are mutable, meaning you can modify their elements by assigning new values to specific indices. Here’s an example:
let languages = ['C', 'Dart', 'JavaScript', 'Kotlin', 'Swift'];
// Modify the value at index 0 to C++
languages[0] = 'C++';
// [ 'C++', 'Dart', 'JavaScript', 'Kotlin', 'Swift' ]
console.log(languages);
Array Length and Manipulation
The length property of an array returns the number of elements it contains. You can modify the length property to resize or truncate an array. Here’s an example:
let numbers = [1, 2, 3, 4, 5];
// Output: 5
console.log(numbers.length);
numbers.length = 3;
// Output: [ 1, 2, 3 ]
console.log(numbers);
Array Iteration and Manipulation Methods
JavaScript provides numerous built-in methods to manipulate and iterate over arrays. Some commonly used methods include push(), pop(), shift(), unshift(), concat(), slice(), splice(), forEach(), map(), filter(), and more. Here’s an example of using the forEach() method:
let numbers = [1, 2, 3, 4, 5];
// Iterating over array elements
numbers.forEach((number) => {
// Print the number to the console
console.log(number);
});
And if, for some reason, you prefer not to use the forEach method to iterate over the array elements, you can also utilize the for loop. Here’s an example that demonstrates how to iterate over array elements using the for loop:
let numbers = [1, 2, 3, 4, 5];
// Iterating over array elements
for (let i = 0; i < numbers.length; i++) {
// Print the number at index i to the console
console.log(numbers[i]);
}
Now, let’s explore how to use some commonly used array methods. These methods provide powerful functionality for manipulating and transforming arrays in JavaScript. Let’s take a closer look:
The push() Method
The push() method adds one or more elements to the end of an array and returns the new length of the array.
let numbers = [1, 2, 3];
// Add 4 and 5 to the numbers array
numbers.push(4, 5);
// Output: [ 1, 2, 3, 4, 5 ]
console.log(numbers);
The pop() Method
The pop() method removes the last element from an array and returns that element.
let numbers = [1, 2, 3, 4, 5];
// Remove the last element, and store in lastElement variable
let lastElement = numbers.pop();
// Output: [ 1, 2, 3, 4 ]
console.log(numbers);
// Output: 5
console.log(lastElement);
The shift() Method
The shift() method removes the first element from an array and returns that element. It also shifts the remaining elements one position down.
let languages = ['C', 'Dart', 'JavaScript', 'Kotlin', 'Swift'];
// Remove the first language, and store it in the fst variable
let fst = languages.shift();
// Output: [ 'Dart', 'JavaScript', 'Kotlin', 'Swift' ]
console.log(languages);
// Output: C
console.log(fst);
The unshift() Method
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
let languages = ['C', 'Dart', 'JavaScript', 'Kotlin', 'Swift'];
// Add 3 more languages to the beginning of the languages array
let length = languages.unshift('C++', 'C#', 'F#')
// Output: [ 'C++', 'C#', 'F#', 'C', 'Dart', 'JavaScript', 'Kotlin', 'Swift' ]
console.log(languages)
// Output: 8
console.log(length)
The slice() Method
The slice() method returns a shallow copy of a portion of an array into a new array. It takes two optional parameters: start (inclusive) and end (exclusive) indices.
let numbers = [1, 2, 3, 4, 5];
// Copy entire array
let sliced1 = numbers.slice();
// Output: [ 1, 2, 3, 4, 5 ]
console.log(sliced1);
// Copy starting from the specified start index
let sliced2 = numbers.slice(2);
// Output: [ 3, 4, 5 ]
console.log(sliced2);
// Copy starting from specified start index, up to. but not including the end index
let sliced3 = numbers.slice(2, 4);
// Output: [ 3, 4 ]
console.log(sliced3);
The splice() Method
The splice() method changes the contents of an array by removing, replacing, or adding elements. It modifies the original array and returns the removed elements as a new array.
Here’s an example that demonstrates how to remove elements from an array using the splice method:
let numbers = [1, 2, 3, 4, 5];
// Remove 2 elements starting from index 0, and store the removed elements in the removedElements variable
let removedElements = numbers.splice(0, 2);
// Output: [ 3, 4, 5 ]
console.log(numbers);
// Print removed elements
console.log(removedElements);
Here’s an example that demonstrates how to replace elements in an array using the splice method:
let numbers = [1, 2, 3, 4, 5];
// Replace 2 elements in the array starting from index 0, with 10, 20, and 30
let replacedElements = numbers.splice(0, 2, 10, 20, 30);
// Output: [ 10, 20, 30, 3, 4, 5 ]
console.log(numbers);
// Print replaced elements
console.log(replacedElements);
Here’s an example that demonstrates how to add elements to an array using the splice method:
let numbers = [1, 2, 3, 4, 5];
// Insert 10, 20, and 30 at index 0
numbers.splice(0, 0, 10, 20, 30);
// Output: [ 10, 20, 30, 1, 2, 3, 4, 5 ]
console.log(numbers);
The concat() Method
The concat() method joins two or more arrays and returns a new array.
let languages1 = ['C', 'Dart', 'JavaScript', 'Kotlin', 'Swift'];
let languages2 = ['C++', 'C#', 'F#', 'Python']
// Join the arrays
let languages = languages1.concat(languages2)
// Output: [ 'C', 'Dart', 'JavaScript', 'Kotlin', 'Swift', 'C++', 'C#', 'F#', 'Python' ]
console.log(languages)
The join() Method
The join() method joins all elements of an array into a string, using a specified separator.
let languages = ['C', 'Dart', 'JavaScript', 'Kotlin', 'Swift'];
// Join languages into a string, separated by a comma, and a space
let string = languages.join(', ')
// Output: C, Dart, JavaScript, Kotlin, Swift
console.log(string)
The indexOf() Method
The indexOf() method returns the first index at which a given element can be found in an array, or -1 if it is not present.
let languages = ['C', 'Dart', 'JavaScript', 'Kotlin', 'Swift'];
// Get index of Dart
let index = languages.indexOf('Dart')
// Output: 1
console.log(index)
The includes() Method
The includes() method checks if an array contains a certain element and returns true or false.
let languages = ['C', 'Dart', 'JavaScript', 'Kotlin', 'Swift'];
let includesDart = languages.includes('Dart')
// Output: true
console.log(includesDart)
The map() Method
The map() method creates a new array by applying a provided function to each element of the calling array.
let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = numbers.map((number) => number * 2);
// Output: [ 2, 4, 6, 8, 10 ]
console.log(doubledNumbers);
We use the map() method to create a new array doubledNumbers where each element is multiplied by 2.
The filter() Method
The filter() method creates a new array with all elements that pass a provided test implemented by the provided function.
let numbers = [1, 2, 3, 4, 5];
let evenNumbers = numbers.filter((number) => number % 2 === 0);
// Output: [ 2, 4 ]
console.log(evenNumbers);
We use the filter() method to create a new array evenNumbers that contains only the even numbers from the original array.
The reduce() Method
The reduce() method applies a function to an accumulator and each element of the array (from left to right) to reduce it to a single value.
let numbers = [1, 2, 3, 4, 5];
let sum = numbers.reduce((accumulator, current) => accumulator + current, 0);
// Output: 15
console.log(sum);
We use the reduce() method to calculate the sum of all numbers in the array. The initial value of the accumulator is set to 0, and the callback function adds each element to the accumulator.
The sort() Method
The sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts elements as strings based on their Unicode code points.
let languages = ['F#', 'C', 'Python', 'PHP', 'Dart', 'JavaScript', 'Kotlin', 'C#', 'Swift', 'C++'];
// Sort the languages array
languages.sort()
// Output: [ 'C', 'C#', 'C++', 'Dart', 'F#', 'JavaScript', 'Kotlin', 'PHP', 'Python', 'Swift']
console.log(languages);
The sort() method is used to sort the languages array in alphabetical order.
However, note that the sort() method sorts elements as strings by default. If you want to sort numbers in ascending order, you need to provide a compare function.
let numbers = [3, 1, 5, 2, 4];
// Sort numbers in ascending order
numbers.sort(function(a, b) {
return a - b;
});
// Output: [ 1, 2, 3, 4, 5 ]
console.log(numbers);
A compare function is passed to the sort() method to sort the numbers array in ascending order.
The reverse() Method
The reverse() method reverses the order of elements in an array in place. The first element becomes the last, and the last element becomes the first.
let numbers = [1, 2, 3, 4, 5];
// Reverse the order of elements in the numbers array
numbers.reverse();
// Output: [ 5, 4, 3, 2, 1 ]
console.log(numbers);
Multidimensional Arrays
JavaScript arrays can also be multidimensional, allowing you to create arrays of arrays. This is useful for representing matrices or grids. Here’s an example:
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Access the value at row 0, column 1
let value = matrix[0][1]
// Output: 2
console.log(value);
Array Destructuring
Array destructuring allows you to extract values from arrays and assign them to variables in a concise way. Here’s an example:
let languages = ['C', 'Dart', 'JavaScript', 'Kotlin', 'Swift'];
// Extract the first and second languages from the languages array
let [fst, snd] = languages;
// Output: C
console.log(fst);
// Output: Dart
console.log(snd);
Conclusion
We covered the fundamentals of JavaScript arrays. We explored how to create arrays, access and modify array elements, manipulate array length, use array iteration and manipulation methods, work with multidimensional arrays, perform common array operations, and utilize array destructuring. Arrays are an essential tool in JavaScript programming, and mastering their usage will greatly enhance your ability to build powerful applications.
Arrays provide a flexible and efficient way to handle collections of data. By understanding the concepts and techniques presented in this article, you are well-equipped to leverage the full potential of arrays in your JavaScript projects.
Sources:
I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!