In JavaScript, you can use a for loop to iterate over an array and perform operations on each element. This loop starts with a variable set to zero and continues until the variable is less than the length of the array. Inside the loop, you can access and manipulate each element using its index.
for (let i = 0; i < array.length; i++) {
// code to be executed for each element
}
let i = 0
initializes the loop counter variablei
to zero.i < array.length
specifies the loop condition: the loop will continue as long asi
is less than the length of the array.i++
increments the loop counter variablei
after each iteration of the loop.
You can access each element of the array using its index: array[i]
.
JavaScript for loop-over array examples
Simple example code we have an array of numbers and we want to print each number to the console.
<!DOCTYPE html>
<html>
<body>
<script>
const array = [1, 2, 3, 4, 5];
for (let i = 0; i < array.length; i++) {
console.log("Array index",i, "element->" , array[i]);
}
</script>
</body>
</html>
Output:
Updating the values of an array
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] * 2;
}
console.log(numbers);
Calculating the sum of an array
const numbers = [1, 2, 3, 4, 5];
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
console.log(sum);
Filtering an array
const words = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
const filteredWords = [];
for (let i = 0; i < words.length; i++) {
if (words[i].length > 5) {
filteredWords.push(words[i]);
}
}
console.log(filteredWords);
D comment if you have any doubts or suggestions on this Js for loop topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version