foreach array helper in javascript
Explore our JavaScript category, where you’ll find loads of helpful articles and tutorials for everyone, whether you’re just starting out or a pro developer. Learn about different JavaScript functions that can be used in various projects according to their specific requirements.
This JavaScript code defines an array of colors and an array of numbers, and then it demonstrates different ways to iterate through these arrays and perform various operations. Here’s a breakdown of the code:
<script>
console.log(colors[i]);
}
console.log(color);
});
sum += number;
}
sum += number;
});
</script>
// Define an array of colors
var colors = ["Red", "Green", "Black"];// Use a for loop to iterate through the colors array and log each color
for (var i = 0; i < colors.length; i++) {console.log(colors[i]);
}
// Use the forEach method to iterate through the colors array and log each color
colors.forEach(function (color) {console.log(color);
});
// Define an array of numbers
var numbers = [1, 2, 3, 4, 5];
// Initialize a variable to store the sum of numbers
var sum = 0;
// Define a function called adder that adds a number to the sum
function adder(number) {sum += number;
}
// Use the forEach method to iterate through the numbers array and call the adder function
numbers.forEach(adder);
// Use the forEach method with an anonymous function to iterate through the numbers array and directly add to the sum
numbers.forEach(function (number) {sum += number;
});
// Log the final sum after iterating through the numbers array
console.log(sum);</script>
In summary:
1- The code prints each color in the “colors” array twice: once using a for loop and once using the forEach method.
2- The code calculates the sum of the numbers in the “numbers” array using two different approaches: by calling a separate adder function with forEach and by directly adding the numbers within an anonymous function passed to forEach.
3- Finally, it logs the total sum of the numbers.