As a JavaScript developer, one of the most fundamental data structures you'll work with is the array. At its core, an array is simply a collection of items, like a list or a sequence. However, in JavaScript, arrays are much more powerful than that.
An array in JavaScript can hold any type of data, including strings, numbers, objects, and even other arrays. This is because JavaScript is a dynamically typed language, which means that variables do not have a fixed data type and can hold values of any type.
For example, you could create an array to store the names of your friends, or you could create an array to store the scores of a game. You could even create an array to store other arrays.
In this article, we'll take a closer look at arrays in JavaScript. We'll also cover different ways arrays can be created, how arrays are accessed, how to detect an array, some of the different categories of array methods, and how each category has its own methods.
By the end of this article, you'll have a solid foundation of arrays in JavaScript and how they can be used to solve problems. So let's get started!
Creating an Array
There are two ways to create an array in JavaScript: using the Array constructor or array literal notation.
Let's look at each comprehensively, backing it up with examples.
1. Using the Array constructor:
let colors = new Array(); // creates an empty array
let numbers = new Array(5); // creates an array with an initial length of 5
let fruits = new Array("apple", "banana", "cherry"); // creates an array with initial values
Output:
[]
[ <5 empty items> ]
[ 'apple', 'banana', 'cherry' ]
2. Using array literal notation:
let colors = []; // creates an empty array
let numbers = [1, 2, 3, 4, 5]; // creates an array with values
let fruits = ["apple", "banana", "cherry"]; // creates an array with values
Output:
[]
[ 1, 2, 3, 4, 5 ]
[ 'apple', 'banana', 'cherry' ]
Accessing Array Elements
To get and set array values, you use square brackets and provide the zero-based numeric index of the value, as shown here:
let colors = ["red", "blue", "green"];
console.log(colors[0]); // Output: "red"
colors[2] = "black"; // changing the value at index 2
console.log(colors); // Output: ["red", "blue", "black"]
Output:
red
[ 'red', 'blue', 'black' ]
From the output, the colors[2] have been changed from green to black and we also used the square brackets to access the first index.
Before we start looking at the different categories of array methods. Let's understand what array length is as a topic that needs to be studied.
Array Length
The length property of an array represents the number of items it contains. It can be accessed and modified.
let colors = ["red", "blue", "green"];
console.log(colors.length); // Output: 3
let names = [];
console.log(names.length); // Output: 0
names.length = 2;
console.log(names[2]); // Output: undefined
console.log(names); // Output: ["ayo", "dapo"]
Let's understand this code comprehensively;
colors is an array that contains three elements: "red", "blue", and "green".
console.log(colors.length) outputs the length of the colors array, which is 3.
names is an empty array with no elements.
- console.log(colors.length) outputs the length of the names array, which is 0.
We change the length of the names array to 2 by assigning a value to its length property: names.length = 2
- This removes any elements beyond the new length, so the third element becomes undefined.
console.log(names[2]) outputs the element at index 2 of the names array, which is undefined because we only have elements at indices 0 and 1.
console.log(colors.length) outputs the entire names array, which contains the elements "ayo" and "dapo" at indices 0 and 1 respectively.
Detecting Arrays
The Array.isArray() method can be used to determine if a value is an array.
const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // Output: true
const str = "hello";
console.log(Array.isArray(str)); // Output: false
Categories of Array Method
We have different categories of array methods in javascript. They are listed below:
Conversion Methods
Stack Methods
Queue Methods
Reordering Methods
Manipulation Methods
Location Methods
Iterative Methods
Reduction Methods
Now, let's address each method comprehensively with examples.
1. Conversion Method
In JavaScript, several conversion methods can be used to convert arrays to other data types or structures. However, in the context of working with arrays, these methods can be thought of as ways to convert or transform an array in some way.
i. toString(): This method converts an array to a string by concatenating all the elements of the array, separated by commas.
const arr = ["apple", "banana", "cherry"];
const str = arr.toString(); // "apple,banana,cher
By using the toString() method, the array arr is converted into a string representation where the elements are separated by commas.
ii. join(): This method concatenates all the elements of the array into a single string, separated by the specified separator.
const joinFruit = ["apple", "banana", "cherry"];
const result = joinFruit.join(" and ");
console.log(result) // // "apple and banana and cherry"
In the provided code, the join() method is used to concatenate the elements of the joinFruit array into a single string with the specified separator " and ".
iii. concat(): This method combines two or more arrays into a single array.
const fruit1 = ["apple", "banana"];
const fruit2 = ["cherry", "mango"];
const combinedFruit = fruit1.concat(fruit2);
console.log(combinedFruit) //// ["apple", "banana", "cherry", "mango"]
In the provided code, the concat() method is used to combine two arrays, fruit1 and fruit2, into a single array called combinedFruit.
iv. slice(): This method returns a new array that is a subset of the original array. You can specify the starting and ending indices of the subset.
Syntax:
array.slice(start, end)
Let's break down the syntax:
array: The original array from which you want to extract elements.
start (optional): The index at which to begin extraction. If omitted, slice() will start from index 0. If negative, it indicates an offset from the end of the array.
end (optional): The index at which to end extraction. The slice() method extracts up to, but not including, the element at the end index. If omitted, slice() will extract all elements from the start index to the end of the array. If negative, it indicates an offset from the end of the array.
Example to better solidify the syntax:
const sliceFruit = ["apple", "banana", "cherry", "mango"];
const subset = sliceFruit.slice(1, 3); // ["banana", "cherry"]
The slice() method is called on the sliceFruit array with two arguments: the starting index and the ending index (exclusive) of the subset to be extracted. The starting index is 1 and the ending index is 3, so the subset will include elements from index 1 up to, but not including, index 3.
v. reverse(): This method reverses the order of the elements in the array.
const reverseFruit = ["apple", "banana", "cherry"];
console.log(reverseFruit.reverse()); // ["cherry", "banana", "apple"]
vi. sort(): This method sorts the elements of the array in ascending order.
Syntax:
array.sort(compareFunction)
The array refers to the array you want to sort, and compareFunction is an optional parameter representing the comparison function.
The compareFunction is responsible for defining the sort order. It should take two elements (a and b) as parameters and return a negative value if a should be sorted before b, a positive value if a should be sorted after b, or 0 if a and b are considered equal.
I understand this might seem difficult at first to understand. I get it! Am here for you. Let me re-explain.
To specify the sort order, the comparison function needs to return a value based on the relationship between a and b. Here's what each return value indicates:
If the comparison function returns a negative value, it means a should be sorted before b. In other words, a comes first in the sorted array.
If the comparison function returns a positive value, it means a should be sorted after b. In other words, b comes first in the sorted array.
If the comparison function returns 0, it means a and b are considered equal in terms of sorting. Their relative order in the original array will be maintained in the sorted array.
Now, that we are on the same page. Let's look at one example to solidify the syntax
const sortNumber = [10, 5, 7, 2];
sortNumber.sort((a, b) => a - b);
console.log(sortNumber); // [2, 5, 7, 10]
To achieve this, we use the sort() method on the sortNumber array. Inside the sort method, we passed a comparison function (a - b) => (a - b).
The comparison function subtracts b from a (a-b). This subtraction results in a negative value if a is smaller than b, a positive value if a is larger than b, and 0 if a and b are equal. This determines the sort order of the elements.
In this case, subtracting b from a will yield the following values:
10 - 5 = 5 (positive value): Since the result is positive, 10 is considered greater than 5, so the order of these elements will be swapped.
5 - 7 = 2 (negative value): Since the result is negative, 5 is considered less than 7, so their order remains unchanged.
7 - 2 = 5 (positive value): Since the result is positive, 7 is considered greater than 2, so the order of these elements will be swapped
After sorting the array using the comparison function, the new order of the elements in the sortNumber array will be [2, 5, 7, 10]
2. Stack Methods in Array
Arrays can be used to implement a stack, which follows the "last-in, first-out" (LIFO) principle. Before we dive in the methods used in stack. I want to clariy what LIFO means.
Last-in, first-out" (LIFO) is a principle that describes the behavior of a data structure where the last item added to the structure is the first one to be removed.
In JavaScript, you can think of a LIFO structure as a stack of books. When you add a new book to the stack, you place it on top of the existing books. If you want to remove a book from the stack, you can only take the one from the top.
The two common methods used in stack are:
i. push(): This method adds one or more elements to the top of the stack.
const stack = ["Book 1", "Book 2"];
stack.push("Book 3", "Book 4");
console.log(stack); // Output: ["Book 1", "Book 2", "Book 3", "Book 4"]
ii. pop(): This method removes and returns the top element of the stack
onst stack = ["Book 1", "Book 2", "Book 3", "Book 4"];
const popped = stack.pop();
console.log(popped); // "Book 4"
console.log(stack); // ["Book 1", "Book 2", "Book 3";
Book 4 was the last to be added in the stack but was the first to be removed. Now, you understand why push() and pop() method are commonly used for stack method.
3. Queue Methods
A queue is a data structure that operates on a "first-in, first-out" (FIFO) basis, which means that the first element that is added to the queue is the first one to be removed. In JavaScript, arrays can be used to represent a queue by using the push() method to add elements to the end of the array, and the shift() method to remove the first element from the beginning of the array.
i. push(): Adds element to the end of the array and returns the new length of the array.
const myQueue = [];
myQueue.push('apple');
myQueue.push('banana');
myQueue.push('cherry');
console.log(myQueue) //[ 'apple', 'banana', 'cherry' ]
Following FIF0; apple was the first to be stored, followed by banana, then cherry.
ii. shift(): removes the first element from the beginning of the array and and returns that element.
Let's see FIFO, in action by removing the first element that was stored in the array.
console.log(myQueue.shift()); // Output: 'apple'
console.log(myQueue.shift()); // Output: 'banana'
console.log(myQueue.shift()); // Output: 'cherry'
From the output, we can see the first to be added was removed using shift() .
apple added first => removed first
banana added second => removed second
cherry added third => removed third.
That is all you need to know about Queue method using push() and shift()
Additionally, the unshift() method can add items to the front of the array, and the pop() method can remove items from the end, allowing for the emulation of a queue in the opposite direction.
iii. unshift(): it adds any number of items to the front of an array and returns the new array length. By using unshift() in combination with pop(), it’s possible to emulate a queue in the opposite direction, where new values are added to the front of the array and values are
const queue = [];
// Emulating a queue using unshift() and pop()
queue.unshift("Ayodele"); // Add "Ayodele" to the front of the queue
queue.unshift("James"); // Add "James" to the front of the queue
queue.unshift("Dapo"); // Add "Dapo" to the front of the queue
console.log(queue); // Output: [ 'Dapo', 'James', 'Ayodele' ]
queue.pop(); // Remove the last person from the queue
queue.pop(); // Remove the next person from the queue
console.log(queue); // Output: [ 'Dapo' ]
Look at the code carefully to see what really happened. In the example, we start with a queue containing an empty array. To emulate a queue called "FIFO" First in First out" using the unshift() and pop() methods, we add new people to the front of the queue using unshift() and remove people from the end of the queue using pop()
Ayodele added first with unshift() \=> Removed first with pop()
James added second with unshift() \=> Removed after James with pop()
The last we have in the array is Dapo.
4. Reordering Methods
Two methods deal directly with the reordering of items already in the array: reverse() and sort(). As one might expect,
i. reverse(): reverses the order of items in an array.
const values = [1, 2, 3, 4, 5];
values.reverse();
console.log(values); //5,4,3,2,1
ii. sort(): This method is used to sort the elements of an array in place. It sorts the elements in ascending order by default, but you can also provide a function to specify your own sorting order. The sort() method returns the sorted array
const sortNumber = [10, 5, 7, 2];
sortNumber.sort((a, b) => a - b);
console.log(sortNumber); // [2, 5, 7, 10]
5. Manipulation Methods
concat(), slice(), splice(), These three methods are indeed commonly classified as manipulation methods due to their ability to modify, extract, combine, or insert elements within arrays. Let's address each of them.
A. concat(): There are various ways to work with the items already contained in an array. The concat() method, for instance, allows you to create a new array based on all of the items in the current array.
This method begins by creating a copy of the array and then appending the method arguments to the end and returning the newly constructed array.
Here's how it works:
i. Cloning the Array: concat() begins by creating a copy of the original array, preserving its elements. This ensures that the original array remains intact, preventing any unintended modifications.
const originalArray = [1, 2, 3];
const clonedArray = originalArray.concat();
console.log(originalArray);
// Output: [1, 2, 3]
console.log(clonedArray);
// Output: [1, 2, 3]
ii. Appending New Items: Next, concat() appends the method arguments to the end of the copied array. If no arguments are passed in, it simply returns a clone of the original array, providing an easy way to duplicate an array.
const originalArray = [1, 2, 3];
const newArray = originalArray.concat(4, 5);
console.log(originalArray);
// Output: [1, 2, 3]
console.log(newArray);
// Output: [1, 2, 3, 4, 5]
iii. Combining Multiple Arrays: When one or more arrays are passed as arguments, concat() adds each item from these arrays to the end of the newly constructed array. This enables you to merge multiple arrays into a single array, simplifying data manipulation and processing.
const array1 = [1, 2, 3];
const array2 = [4, 5];
const array3 = [6, 7, 8];
const combinedArray = array1.concat(array2, array3);
console.log(combinedArray);
// Output: [1, 2, 3, 4, 5, 6, 7, 8]
iv. Support for Non-Array Values: Furthermore, concat() can also handle non-array values. If you pass in values that are not arrays, they are simply appended to the resulting array. This flexibility allows you to mix arrays and individual values seamlessly.
const array1 = [1, 2, 3];
const value = 4;
const newArray = array1.concat(value);
console.log(newArray);
// Output: [1, 2, 3, 4]
B. Slice(): This method returns a new array that is a subset of the original array. You can specify the starting and ending indices of the subset. We can use slice() method to manipulate an array by extracting a subset or by creating a shallow copy.
i. Extracting a subset of an array
const sliceFruit = ["apple", "banana", "cherry", "mango"];
const subset = sliceFruit.slice(1, 3);
console.log(subset); // ["banana", "cherry"]
In the example above, the slice method was used to extract banana and cherry from the original array and put it in new array without manipulating or change the original array. We can see that in action in the code below.
const sliceFruit = ["apple", "banana", "cherry", "mango"];
const subset = sliceFruit.slice(1, 3);
console.log(subset); // ["banana", "cherry"]
console.log(sliceFruit); //["apple", "banana", "cherry", "mango"];
We can see the sliceFruit remains intact even after extracting banana and cherry.
ii. Creating shallow copy
const sliceFruit = ["apple", "banana", "cherry", "mango"];
const copyFruit = sliceFruit.slice()
console.log(sliceFruit)
The slice() method will return a new array that contains a copy of all the elements from the original array.
C. splice(): The most powerful array method is splice(), which can be used in a variety of ways. Unlike slice(), which extracts elements to create a new array, splice() modifies the original array by adding or removing elements at a specified index.
splice syntax:
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2, itemN)
The splice method can be used for three things:
Adding Elements
Removing Elements
Modifying Elements
Let's look at each comprehensively with relatable examples to back it up.
i. Splice() to Adding Elements:
The splice() method can be used to add elements to an array. By specifying the index at which to add elements and providing the new elements as arguments, you can insert them into the original array. The existing elements at and after the specified index are shifted to accommodate the new elements.
Example:
const addingArray = [1, 2, 3, 4, 5];
addingArray.splice(2, 0, 6, 7);
console.log(addingArray); // Output: [1, 2, 6, 7, 3, 4, 5]
Using this syntax to solve the above example.
splice(start, deleteCount, item1, item2, ...).
From the code we start at index 2, removing 0 element , added 6 and 7 respectively.
ii. Splice() to Remove Elements:
splice() can remove elements from an array. By specifying the index at which to start removing elements and the number of elements to be removed, you can eliminate them from the original array. The remaining elements are then adjusted to fill the gap left by the removed elements.
const removeArray = [1, 2, 3, 4, 5];
//Syntax: splice(start, deleteCount, item1, item2, ...).
removeArray.splice(1, 2);
console.log(removeArray );
// Output: [1, 4, 5]
Using the splice syntax, we started from index 1, removing 2 elements(2, 3 respectively).
iii. Splice() to Modify Elements:
splice() can also be used to modify elements within an array. By specifying the index of the element to be modified and providing new values as arguments, you can replace the existing element with the new values, effectively modifying the original array. Let's look at an example to defend this.
const modifyArray = [1, 2, 3, 4, 5];
//Syntax:
//splice(start, deleteCount, item1, item2, itemN)
modifyArray.splice(2, 1, 6);
console.log(modifyArray );// Output: [1, 2, 6, 4, 5]
In the example, we use splice() to modify the element at index 2 of the originalArray. We replace the existing element 3 with the new value 6, effectively modifying the original array.
6. Location Methods
There are methods that allow you to locate items within an array:
i. indexOf(): method starts searching from the front of the array (item 0) and continues to the back.
Syntax
//Syntax and Arguments of indexOf():
array.indexOf(item, start)
Let's break down the syntax
array is the array in which we want to search for the item.
item is the element we are looking for within the array.
start (optional) specifies the index position from where the search should begin. If not provided, the search starts from the beginning of the array.
Now that we are on the same page with the syntax. Let's try a code example.
const numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
console.log(numbers.indexOf(4)); // 3
console.log(numbers.indexOf(4, 4)); // 5
The first indexOf() call looks for the first occurrence of the number 4 in the numbers array. It starts the search at the beginning of the array, and returns the index of the first occurrence of 4, which is 3. console.log(numbers.indexOf(4)); // 3
The second indexOf() call looks for the first occurrence of the number 4 in the numbers array, but it starts the search at index 4. This means that it will ignore the first occurrence of 4, which is at index 3, and will instead look for the next occurrence of 4, which is at index 5. console.log(numbers.indexOf(4, 4)); // 5
ii. lastIndexOf() starts from the last item in the array and continues to the front.
Syntax:
array.lastIndexOf(item, start)
array is the array in which we want to search for the item.
item is the element we are looking for within the array.
start (optional) specifies the index position from where the backward search should begin. If not provided, the search starts from the end of the array.
Example:
const numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
console.log(numbers.lastIndexOf(4)); // 5
console.log(numbers.lastIndexOf(4, 4)); // 3
The first lastIndexOf() call in the code above looks for the last occurrence of the number 4 in the numbers array. It starts the search at the end of the array, and returns the index of the last occurrence of 4, which is 5.
The second lastIndexOf() call looks for the last occurrence of the number 4 in the numbers array, but it starts the search at index 4. This means that it will ignore all of the occurrences of 4 that come before index 4, and will instead look for the last occurrence of 4 that comes after index 4. The last occurrence of 4 that comes after index 4 is at index 3, so that is the value that is returned.
iii. includes(): The includes() method in JavaScript is used to determine whether an array contains a specific element. It checks if the array includes the specified value and returns a boolean (true or false) indicating the result.
Syntax
array.includes(valueToFind)
Example
const fruits = ["apple", "banana", "cherry"];
console.log(fruits.includes("banana")); // Output: true
console.log(fruits.includes("orange")); // Output: false
iv. find(): The find() method searches an array for the first element that satisfies a given condition. It takes a callback function as an argument, which is executed for each element in the array. The callback function returns a boolean value indicating whether the element matches the condition. The find() method returns the first element for which the callback function returns true, or undefined if no element is found.
Syntax:
array.find(callbackFunction)
Example:
const numbers = [1, 2, 3, 4, 5];
const foundNumber = numbers.find((number) => number > 3);
console.log(foundNumber); // Output: 4
The code simply checks for the first number that is greater than 3 which is 4.
v. findIndex(): The findIndex() method is similar to find(), but it returns the index of the first element that satisfies the given condition, rather than the element itself. It takes a callback function as an argument, which is executed for each element in the array. The callback function should return true if the element matches the desired condition, or false otherwise. The findIndex() method returns the index of the first matching element, or -1 if no element is found
Syntax:
array.findIndex(callbackFunction)
Example:
const numbers = [10, 20, 30, 40, 50];
const foundIndex = numbers.findIndex((number) => number > 20);
console.log(foundIndex); // Output: 2
findIndex() returned index 2 because that is the first index that matches our condition.
The find() and findIndex() methods will be comprehensively discussed in my upcoming article, "Data Transformation Using Array Methods." Stay tuned
7. Iterative Method
ECMAScript 5 defines five iterative methods for arrays. Each of the methods accepts two arguments: a function to run on each item. The function passed into one of these methods will receive three arguments: the array item value, the position of the item in the array, and the array object itself.
Let's look at the 5 iterative methods comprehensively.
i. every() - method tests whether all elements in the array pass the test implemented by the provided callback function. It returns a boolean value indicating whether all elements satisfy the condition or not.
const array = ['apple', 'banana', 'cherry', 'date'];
const allStrings = array.every(item => typeof item === 'string');
console.log(allStrings); // Output: true
The every() method returns true if all elements are string.
ii. some() - method tests whether at least one element in the array passes the test implemented by the provided callback function. It returns a boolean value indicating whether such an element exists in the array or not..
Example
const numbers= [1, 3, 5, 7, 8, 9];
const containsEven = array.some(item => item % 2 === 0);
console.log(containsEven); // Output: true
It checked if at least one item satisfies is even number. Number 8 satisfies the condition, 8 / 2 = 4
iii. filter(): method creates a new array with all elements that pass the test implemented by the provided callback function. It does not modify the original array..
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evenNumbers = nums.filter(item => item % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6, 8, 10]
It filters out all the item to get only the even numbers that satisfies the condition and puts them in new array.
In the example above all the item that satisfies the condition of dividing by 2 without any remainder are 2 , 4 , 6, 8, 10. It puts all in new array [2, 4, 6, 8, 10]
iv. forEach(): is used to loop through an array and perform an action on each element. It allows you to execute a provided function once for each element in the array. It does not create a new array or modify the original array.
const fruit = ['apple', 'banana', 'cherry'];
fruit.forEach(item => console.log(item));
Output:
apple
banana
cherry
In the provided example , The forEach() logged each element of the array without creating new array or modifying the existing array
v. map(): The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. It applies the provided callback function to each element of the array and returns a new array with the results.
const names = ['john', 'jane', 'bob'];
const uppercaseNames = names.map(item => item.toUpperCase());
console.log(uppercaseNames); // Output: ['JOHN', 'JANE', 'BOB']
It created a new array by working on each item to convert each item to uppercase.
In addition to the five methods introduced by ECMAScript 5, flatMap is another iterative methods introduced by ECMAScript 2019 (ES10). It will be discussed fully in "Data Transformation Using Array Methods." Stay tuned!
8. Reduction Methods
The reduce() method is used to reduce the elements of an array into a single value. It takes a callback function as an argument and executes that function on each element of the array, resulting in a single value. The callback function takes four arguments: the accumulator, current value, current index, and the array itself.
i. reduce(): The method allows you to iteratively process each item in an array, gradually building up a final value. It starts from the first item and proceeds towards the last.
Let me introduce you to the syntax before using the syntax.
Syntax
reduce(callbackFn)
reduce(callbackFn, initialValue)
In reduce method, The value returned by the function becomes the first argument for the next item, allowing you to accumulate results as you progress.
What do we mean by the function becomes the first argument for the next item?
Lets look at some examples.
Example 1: Without initial value
//reduce(callbackFn)
1. const numbers = [1, 2, 3, 4, 5];
const multipliedResult = numbers.reduce(function(prev, cur, index, array) {
return prev * cur;
});
console.log(multipliedResult); // Output: 120
Lets solve this example mathematically since we are dealing with numbers!
During each iteration, the callback function multiplies the current value (cur) with the accumulated value (prev). The result of this multiplication becomes the first argument (prev) for the next iteration. This process continues until all items in the array have been processed.
Let's break down the iterations:
First iteration: prev = 1 (initial value), cur = 2, result = 2 * 1 = 2
Second iteration: prev = 2 (previous result), cur = 3, result = 2 * 3 = 6
Third iteration: prev = 6 (previous result), cur = 4, result = 6 * 4 = 24
Fourth iteration: prev = 24 (previous result), cur = 5, result = 24 * 5 = 120
Example 2: With Initial value
//Using this syntax: reduce(callbackFn, initialValue)
const numbers = [10, 20, 30, 40, 50];
const sumWithInitialValue = numbers.reduce(function(prev, cur) {
return prev + cur;
}, 100);
console.log(sumWithInitialValue); // Output: 250
Let's break down the iterations:
Now, we have the initial value to be 100.
First iteration: prev = 100 (initial value), cur = 10, result = 100 + 10 = 110
Second iteration: prev = 110 (previous result), cur = 20, result = 110 + 20 = 120
Third iteration: prev = 130 (previous result), cur = 30, result = 130 + 30 = 160
Fourth iteration: prev = 160 (previous result), cur = 40, result = 160 + 40 = 200
Fifth iteration: prev = 200 (previous result), cur = 50, result = 200 + 50 = 250.
Conclusion
In conclusion, arrays are a fundamental data structure in JavaScript that allow you to store and manipulate collections of values. They can hold any type of data and provide numerous built-in methods for creating, accessing, modifying, and iterating over the elements.
In this article, we covered the basics of arrays, including ways to create arrays, accessing elements, manipulating arrays using various methods such as concat(), slice(), splice(), and more. We also explored location methods like indexOf(), lastIndexOf(), and iterative methods like every(), some(), filter(), forEach(), and reduce().
Understanding arrays and their methods is essential for JavaScript developers as they form the backbone of many algorithms and data manipulations. By leveraging the power of arrays, you can efficiently work with collections of data in your JavaScript applications.
Remember to experiment with these concepts and methods to deepen your understanding and improve your skills as a JavaScript developer.