Data is essential to all JavaScript applications. It determine what we see, hear and interact with when we open the app, and it must be stored properly to guarantee a smooth user experience. Specifically, the data must be a stored in a way that facilitates retrieval, manipulation and is efficient in storage usage. need data to represent information.
One of the most important prominent data structures in JavaScript is known as an Array. This is a collection of related elements, usually of the same data type, which can be accessed and manipulated using index numbers.
In this article, we will learn about Arrays and the operations we can perform with them. We will also explore the usage of many built-in array methods, with examples.
A JavaScript Array is a JavaScript object that can hold multiple values of different types. It is an ordered list of elements, identified by their index. Arrays in JavaScript can contain any combination of numbers, strings, objects, or even other arrays. This flexibility makes arrays a powerful tool for organizing and manipulating data.
Creating JavaScript Arrays
In JavaScript, arrays can be created using square brackets [] or the Array() constructor.
Using Array Literals
For example, the following code creates an array of strings:
let fruits = ["apple", "banana", "orange"];
We can access individual elements of an array using its index numbers. The index of the first element is always 0, and the index of the last element is always the length of the array, minus one. For example:
In JavaScript, arrays can also contain elements of different data types, such as numbers, strings, booleans, JavaScript objects, and even other arrays to create a nested array. For example:
To explain it visually, the image below shows how the elements of an array fit into the respective indexes.
Using the Array constructor
If you want to use a traditional Array() constructor, you can also create an array following the next code:
// Creating an array with multiple elements
let fruits = new Array('apple', 'banana', 'orange');
console.log(fruits); // Output: ['apple', 'banana', 'orange']
You can also create empty arrays to with an specific length that you can fill with your items later.
// Creating an array with a specific length
let emptyArray = new Array(5);
console.log(emptyArray.length); // Output: 5
JavaScript Array Length
The length of an array in JavaScript is the number of elements stored in the array. This is a property of the array object, and is accessible using the length property. The length property of an array is automatically updated when elements are added to or removed from the array.
Here’s an example of how to use the length property to determine the number of elements in an array:
In this example, we have an array called numbers that contains five elements. We use the length property to get the number of elements in the array, which is 5.
As you can see, we are using JavaScript’s console log. As a JavaScript developer it’s important that you learn how to use and take advantage of JavaScript browser console, so we recommend you to check out the following article:
The length property can also be used to change the size of an array by assigning a new value to it. For example, if we assign a smaller value to the length property, the array will be truncated:
In this example, we assign the value 3 to the length property of the numbers array. As a result, the last two elements of the array are removed, and the array now contains only three elements.
On the other hand, if we assign a larger value to the length property, the array will be extended, and the new elements will be set to undefined:
In this example, we assign the value 7 to the length property of the numbers array. As a result, the array is extended with two new elements set to undefined.
It’s important to note that the length property does not always correspond to the number of defined elements in the array. For example, if we create an array with a length property of 5 but only define three elements, the length property will still be 5.
In this example, we create an array with three defined elements but then assign a length of 5. As a result, the last two elements of the array are set to undefined, and the length property is 5.
Dealing with Dates and Time is a daily work as a developer, if you want to understand and become a master in dealing with JavaScript dates read our article about JavaScript Dates.
JavaScript provides many built-in methods that can be used to manipulate arrays. Here’s a list of some of the most commonly used JavaScript array methods with examples:
JavaScript Array push()
When you want to add one or more elements to the end of an array, use the push() method. In the code snippet below, we add a new string, “kiwi”, at the end of the fruits array. The push() method modifies the original array.
The pop() method removes the last element of an array and returs it, thereby modifying the original array. In the code example below, we remove the string “orange” using the pop() method.
While pop() removes the last element of the array, shift() helps you to remove the first element of an array and returns it. In the code example below, we have removed the first element, “apple”, from the given array using the shift() method.
The slice() method returns a new array that contains a portion of the original array, and you can provide the parameters to indicate how to slice out the portion of the array. Please note, however, that the slice operation will not change the original array.
The splice() method may sound similar to the slice() method, but they’re used for entirely different purposes. Whereas the slice() method returns a portion of the original array, the splice() method changes the content of an array by removing or replacing existing elements and/or adding new ones.
The parameters of the splice() method look like these:
As the name suggests, the reverse() method reverses the order of elements in an array. It’s important to highlight the fact that this method changes the input array itself.
The sort() method sorts the elements of an array. It performs an ascending sort by default and converts the elements into strings while sorting. Sorting an array of string with the sort() method is straightforward.
The join() method converts an array to a string. To avoid confusing this method with the concat() method, where two or more array elements merge, you can pass a specifier to the join method.
When you want to determine whether an array includes a specified element or not, use the includes() method. It will return the value ‘true’ whether the element is included or false.
This method it’s effective for checking if simple, primitive types are present in an array. However, for objects and arrays (complex types), includes() checks for reference equality, not content equality, meaning it looks for the exact same object in memory, not just an object with the same properties or values.
JavaScript Array filter()
The filter() method creates a new array with all elements that pass the test you provide, but remember that you need to provide the test using a callback JavaScript function. In the example below, the test is designed to isolate the even numbers.
This creates a new array with the results of calling a function on every element in the original array. The callback function that invokes every array element can be anything that suits your use cases.
This applies a function against an accumulator and each element in the array, to reduce it to a single value. The example below uses the reduce() method to accumulate the array elements to find their sum.
Unlike the every() method, the some() method tests whether at least one element in the array passes the test provided by a callback function. Again, it returns answers in true or false.
The at() method is a relatively new addition to JavaScript, introduced in ECMAScript 2019. It allows you to retrieve an element from the calling array at a specific index, similar to using square bracket notation with the index.
However, at() also supports negative indexing and returns undefined for out-of-bounds indices instead of throwing an error.
Here’s the basic syntax of the at() method:
array.at(index)
array: The array to retrieve the element from.
index: The index of the element to retrieve. This can be a positive or negative integer.
Here are a few examples to demonstrate the usage of the at() method:
Mastering Asynchronous JavaScript is crucial for effective application development. Explore our in-depth article to enhance your skills in handling asynchronous operations in JavaScript
You can iterate over JavaScript array elements in several ways, from the traditional loops to more advanced and modern methods, let’s explore all the options
Iterating using traditional for loops
The traditional and well-known classic for loop gives you complete control over the iteration process, so you can use it to easily iterate a JavaScript array:
let numbers = [10, 20, 30];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
// Output:
// 10
// 20
// 30
Using JavaScript array forEach() method
You can also use the forEach() method, which executes a provided function once for each array element. It iterates over the elements, as we see in the example below.
Introduced in ES6, the for...of loop is on the simplest methods to iterate over an iterable object like an array.
let fruits = ['apple', 'banana', 'orange'];
for (let fruit of fruits) {
console.log(fruit);
}
// Output:
// apple
// banana
// orange
Using JavaScript array Iterators
An iterator is an object that enables traversal over a collection, in our case a JavaScript array. An iterator provides some methods that allows you to iterate the collection and get the collection items. The most used method is next() which returns the current element and move the iterator to the next object in the collection.
In this FAQ section, we’ll explore some common questions about JavaScript arrays and learn about the common operations you can perform with them.
How do I add elements to a JavaScript array?
To add elements to an existing array, JavaScript provides several array methods. One method is push(), which adds one or more elements to the end of the array. For example, to add a new element to an array called myArray, you can use the following code: myArray.push("newElement");
Another method is unshift(), which adds one or more elements to the beginning of the array. The existing elements are shifted to higher indices. Here’s an example: myArray.unshift("newElement");
How to remove element from array in JavaScript?
Remove an element from an array in JavaScript by using splice(index, 1) for a specific index value, or filter() to conditionally remove elements. For example, array.splice(2, 1); removes the third element.
Using splice
let myArray = ['a', 'b', 'c'];
myArray.splice(1, 1); // Removes the element at index 1 ('b')
console.log(myArray); // Outputs: ['a', 'c']
Using filter
let myArray = ['a', 'b', 'c', 'b'];
myArray = myArray.filter(element => element !== 'b'); // Removes all instances of 'b'
console.log(myArray); // Outputs: ['a', 'c']
How to sort an array in JavaScript?
To sort an array in JavaScript, you can use the sort() method, which can optionally take a compare function as an argument. This function is often provided as a lambda (arrow) function, and determines the sort order based on the return value. For numerical sorting, the lambda function typically subtracts one element from another:
let numbers = [3, 1, 4, 2];
numbers.sort((a, b) => a - b); // Sorts the array numerically in ascending order
console.log(numbers); // Outputs: [1, 2, 3, 4]
How to find array length in JavaScript?
Determine the length of an array in JavaScript using the length property. For example, console.log(myArray.length); returns the number of elements in myArray.
let myArray = [1, 2, 3, 4, 5];
console.log(myArray.length); // Outputs the length of the array: 5
How to check if an array is empty JavaScript?
To check if an array is empty in JavaScript use the length property, evaluating array.length === 0. If true, the array is empty.
let myArray = [];
if (myArray.length === 0)
console.log("Array is empty")
else
console.lo("Array is not empty")
How can I merge multiple arrays in JavaScript?
Merge multiple arrays in JavaScript with the concat() method. For instance, const mergedArray = array1.concat(array2, array3); combines array1, array2, and array3.
let array1 = [1, 2];
let array2 = [3, 4];
let mergedArray = array1.concat(array2); // Merges array1 and array2
console.log(mergedArray); // Outputs: [1, 2, 3, 4]
How do I access elements in a JavaScript array?
Access elements in a JavaScript array using bracket notation with indices. For example, const element = array[index]; retrieves the element at index position from the array.
let myArray = ['a', 'b', 'c'];
console.log(myArray[0]); // Outputs the first element: 'a'
console.log(myArray[1]); // Outputs the second element: 'b'
How to convert string to array in JavaScript?
Convert a string to an array in JavaScript using split(). For a comma-separated string, use const array = string.split(',');.
let myString = "a,b,c";
let myArray = myString.split(","); // Splits the string into an array
console.log(myArray); // Outputs: ['a', 'b', 'c']
How to convert a JavaScript array to string?
Convert a JavaScript array to a JavaScript string with join(). For example, const string = array.join(', '); joins array elements with a comma and a space.
How to remove duplicates in array JavaScript?
To remove duplicates from an array in JavaScript, use [...new Set(array)]. This creates a set with unique values and then converts it back to an array.
To find an item in a JavaScript array, use the find() or includes()method. The find() returns the first element that satisfies a provided testing function. If no array item satisfy the testing function, it returns undefined. Here’s an example:
let array = [1, 2, 3, 4, 5];
let foundItem = array.find(element => element > 3); // Finds the first element greater than 3
console.log(foundItem); // Outputs: 4
Use the includes() method to find out if an item exists in a JavaScript array. This method checks if the array contains a specific element and returns true if it does, or false if it does not. However, includes() only checks for the presence of an element.
let myArray = [1, 2, 3, 4, 5];
let hasThree = myArray.includes(3); // Checks if '3' is in the array
console.log(hasThree); // Outputs: true
How to iterate a JavaScript array?
To iterate over a JavaScript array, you can use several methods, including forEach(), for loops, or for…of loops. Here’s how each method works:
Using forEach():
let myArray = [1, 2, 3];
myArray.forEach(element => console.log(element)); // Iterates and logs each element
Using a for loop:
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]); // Accesses each element by index
}
Using a for...of loop:
for (let element of myArray) {
console.log(element); // Directly accesses each element
}
Conclusion
That’s all for now. We hope it was useful and has given you a launchpad to start using the array methods. As a JavaScript developer, you don’t need to remember all the syntaxes of the Array methods. However, you must know their usage to ensure you maximise their benefits and deploy them at the right times.
Tapas Adhikary is a Full Stack Developer. He loves building web apps, mobile apps, and JAMstack solutions. He is a technology blogger who publishes articles for freeCodeCamp, daily.dev, dev.to, his blog.greenroots.info and also in his YouTube Channel. Follow him on Twitter(@tapasadhikary) to stay connected.