JavaScript Array Iteration Methods
JavaScript Array iteration methods perform some operation on each element of an array. Array iteration means accessing each element of an array. JavaScript provides mainly 3 simple statements for looping over each array items.
- for ... of (loops over entries)
- for ... in (loops over indexes)
- forEach (myFunction)
1.The for...of Loop
The for...of statements hands you the array values.
// Create an Array
const cars = ['BMW', 'Volvo', 'Mini'];
// Iterate over the Array values
let text = "";
for (let x of cars) {
text += x + ",";
}
2.The for...in Loop
The for...in statements hands you the array indexes. To make it return the elements you must use [x]. for...in was created to inspect Object properties (like: name, age, height), not Arrays.
// Create an Array
const cars = ['BMW', 'Volvo', 'Mini'];
// Iterate over the Array values
let text = "";
for (let x in cars) {
text += x + ",";
}
// Create an Array
const cars = ['BMW', 'Volvo', 'Mini'];
// Iterate over the Array values
let text = "";
for (let cars[x] in cars) {
text += x + ",";
}
3.JavaScript Array forEach()
The forEach() method calls a function (a callback function) for each array element. The provided function is user-defined, it can perform any kind of operation on an array.
Syntax:
array.forEach(function callback(value, index, array) {
} [ThisArgument]);
Parameters: This function accepts three parameters as mentioned above and described
- value: This is the current value being processed by the
- index: The item index is the index of the current element which was being processed by the
- array: The array on which the .forEach() method was called.
let emptytxt = "";
let Arr = [23, 212, 9, 628, 22314];
function itrtFunction(value, index, array) {
console.log(value);
}
Arr.forEach(itrtFunction);
//output
23
212
9
628
22314 //
4.JavaScript Array map()
The array.map() method creates an array by calling a specific function on each item in the parent array and it does not change the value or element of the array. It does not execute the function for array elements without values.
Syntax:
array.map(function(value, index, array){
}[ThisArgument]);
Parameters: This method accepts three parameters as mentioned above and described
- value: This is the current value being processed by the
- index: The item index is the index of the current element which was being processed by the
- array: The array on which the .map() function was called.
const numbers1 = [45, 4, 9, 16, 25];
const numbers2 = numbers1.map(myFunction);
function myFunction(value, index, array) {
return value * 2;
}
Top comments (1)
Who