In JavaScript, arrays are a data type that is used to store multiple elements in a single variable. JavaScript gives you many built-in methods that help you add, remove, search, and modify elements without writing long and complicated code, which makes working with arrays easier. These array methods save time and make code easier to read. In this blog, we will discuss JavaScript array methods and how to access, manipulate, or delete the elements from the array with the help of basic examples.
Table of Contents:
Array in JavaScript
An array in JavaScript is a special type of object used to store multiple values in a single variable. It allows you to group related data together and access it using an index.
How to Declare an Array in JavaScript:
Declaring an array in JavaScript is the simplest and easiest task. You can declare an array by using square brackets [ ] and store it in a single variable.
Syntax:
let arr = [val1, val2, val3, ...];
JavaScript Array Methods
JavaScript offers you various array methods that will help you to manipulate the original array or allow you to make a copy of a new array. Here’s a list of JavaScript array methods of different categories depending on their functionality:
Iteration Methods
These Array Methods are used to iterate over array elements and perform certain actions on each element. The list of methods with their description is given below:
1. forEach(): The forEach() method is used to iterate over the elements of an array.
Example:
Output:
2. map(): The map() Method is also used to iterate over an array. It applies a function to each element of an array and returns a new array of modified elements.
Example:
Output:
3. filter(): The filter() method is used to create a new array with all elements that pass the specific test condition of a given function.
Example:
Output:
4. reduce(): This method applies a function to each element in the array (from left to right) and reduces it to a single value.
Example:
Output:
5. reduceRight(): This method runs the reducer function for each and every array element. But the difference is as the name suggests, reduceRight(), which means it starts reducing elements from right to left.
Example:
Output:
6. some(): The some() method executes a function for each element of the array and returns the output in the form of true or false.
Example:
Output:
7. every(): The every() method checks whether the given condition written in the callback function is true for every element or not.
Example:
Output:
8. find(): The find() method in JavaScript returns the first element value in the array that satisfies the condition written in the callback function.
Example:
Output:
9. findIndex(): This findIndex() method is used to return the index of the first element that satisfies the condition written in the callback function. If it does not meet the condition, it returns -1.
Example:
Output:
Array Transformation Methods are used to transform or modify arrays in various ways, which are described below:
1. map(): This method creates a new array with the results of applying a function to each element.
Example:
Output:
2. slice(): The slice() method in JavaScript is responsible for returning a shallow copy of an array and creating a new array as output.
Example:
Output:
3. splice(): This method adds or removes elements from an array at a specific index.
Example:
Output:
4. concat(): The concat() method in JavaScript is used to merge two or more different arrays into a single one.
Example:
Output:
5. sort(): The sort() method in JavaScript is used to sort the elements of an array and returns the sorted array.
Example:
Output:
6. reverse(): This method reverses the elements of an array in place.
Example:
Output:
7. join(): The join() method in JavaScript is used to join all the elements of an array into a single string.
Example:
Output:
Array Mutation Methods
Mutation means transforming the original array and returning the modified array. There are several methods that transform the array element, which are described below:
1. push(): The push() method is used to add elements to the end of an array, and it returns the new length of the array as output.
Example:
Output:
2. pop(): The pop() method in JavaScript is used to remove the last element from an array and returns that element.
Example:
Output:
3. shift(): The shift() method is used to remove the first element from an array, and it will return that element after removing it.
Example:
Output:
4. unshift(): This unshift() method in JavaScript adds one or more elements to the start of an array and returns the new length.
Example:
Output:
5. fill(): This method changes all elements in an array to a static value from a start index to an end index.
Example:
Output:
Search Methods
The Search Method helps to find the specific element or its indices in an array.
1. includes(): This method checks if a specific element is present in an array.
Example:
Output:
2. indexOf(): This method returns the first index at which a given element is found in the array or -1 if not found.
Example:
Output:
3. lastIndexOf(): This method returns the last index at which a given element is found in the array.
Example:
Output:
Utility Methods
Utility Methods are helper functions that are used to provide small, reusable pieces of code that serve a specific purpose or perform a particular task in order to manipulate the array. There are several Utility Methods provided by the array, which are described below:
1. copyWithin(): This method makes a Shallow copy of part of an array to another location in the same array and overwrites the existing array values.
Example:
Output:
2. fill(): The fill() method in JavaScript fills all the elements in the array. It can start from the starting index and go up to the end index.
Example:
Output:
3. flat(): This method flattens nested arrays into a single array.
Example:
Output:
4. flatMap(): This method applies a function to each element and flattens the result into a new array.
Example:
Output:
5. from(): The from() method in JavaScript helps you to create a new array instance from an array-like or iterable object.
Example:
Output:
6. keys(): This method returns a new array iterator object that contains the keys (indexes) of the array.
Example:
Output:
7. entries(): The entries() method in JavaScript returns a new array iterator object that can contain the key-value pairs for each index in the array.
Example:
Output:
8. values(): The values() method returns a new array object that contains the values for each index in the array.
Example:
Output:
Testing Methods
The Testing Method in JavaScript Array is used to test or validate conditions on an array. JavaScript provides various methods to check the array, which are described below:
1. some(): The some() method in JavaScript checks for at least one element that satisfies the condition.
Example:
Output:
2. every(): This method checks if all elements satisfy the condition.
Example:
Output:
Common Use Cases for JavaScript Array Methods
Arrays are one of the important data types in JavaScript. Here are some common use cases for different array methods:
- Filtering data: This method will help you create a new array by selecting only the elements that meet a specific condition, like finding all items that are greater than a specific number.
- Transforming data: This method will help you change or update the values in an array, like doubling the numbers or changing the format of each item in the array.
- Reducing an array: This method will help you combine all the elements of an array into a single value, like adding all the numbers to get the total sum.
- Sorting data: This method arranges the elements of an array in a specific order, like sorting numbers from smallest to largest or alphabetically arranging words.
- Iterating over arrays: This method will help you go through each element of an array and perform an action on it, like applying a function to each element or printing each value.
Best Practices and Common Mistakes of JavaScript Array Methods
Here are some best practices and common mistakes you need to keep in mind when you working with array methods in JavaScript:
Best Practices:
- Use const or let: You should use const when you don’t want the array to change itself, and let when you need to change the array later. This will help you avoid accidental changes.
- Use simple array methods: You should use methods like map, filter, and reduce instead of traditional loops. These methods will make your code cleaner and easier to understand.
- Don’t use forEach when you need to return data: forEach is a great method for doing things with each item, but if you want to get a new array or end the loop early, it’s better for you to use map, filter, or a normal for loop.
- Provide a starting value in reduce: When you are using reduce, you should always give it a starting value, like 0, for adding numbers to avoid unexpected results, especially when you are working with empty arrays.
- Know which methods change the array: There are some methods, like sort or reverse, that change the original array. If you don’t want to change the array, then use methods that return new arrays like map, filter, or concat.
Common Mistakes to Avoid:
- Forgetting to pass a function: There are some methods like map, filter, and forEach that need a function to tell them what to do with each item. If you forget to add the function, it will cause an error.
- Changing the array while looping: If you are changing the array while looping through it, it can cause problems. So, you should try to avoid doing this.
- Using sort without a comparison: sort arranges things like text, so you should always provide a way to compare items if you’re sorting numbers or objects.
- Incorrect this in callback functions: When you are using forEach, map, or filter, the ‘this’ keyword inside the function will not point to where you want it to. You can use arrow functions to solve this.
- Not handling empty arrays: There are some methods, like reduce, that do not work correctly on empty arrays. You should always check for empty arrays before using these methods.
- Using splice too much: Splice is very useful, but sometimes can be tricky. For simple tasks, you can use filter or concat instead of splice to avoid errors.
Conclusion
So far in this blog, we have learned different JavaScript array methods and how to access, manipulate, or delete the elements from the array. An array in JavaScript is a special type of object used to store multiple values in a single variable. It allows you to group related data together and access it using an index. There are various JavaScript Array Methods that help to manipulate the original array or make a copy of that array.
FAQ’s
Q1. What is the purpose of the reduce() method in JavaScript arrays?
The reduce() method applies a function to each element in the array from left to right and reduces the array to a single value.
Q2. What is the forEach() method used for?
The forEach() method loops through the given function once for each array element. Unlike map(), it does not return a new array.
Q3. How is the map() method different from forEach() in JavaScript arrays?
The map() method creates and returns a new array by transforming each element, whereas the forEach() method runs a function on each element without returning anything.
Q4. What does reduce() return if the array is empty?
If the array is empty and no initial value is given to the reduce() method, then it will throw a TypeError. However, if an initial value is given, it will return that initial value.
Q5. What is the difference between slice() and splice() in JavaScript?
The slice() method returns a shallow copy of a part of an array without transforming the original array, whereas the splice() method modifies the array by removing or adding elements at a specific index. The splice() Method also returns the removed elements if there are any.