JavaScript ForEach Equivalent
One thing with the For Loop in JavaScript is it doesn’t seem to be very well documented that you can use it to do an equivalent of a ForEach loop.
Here’s a short example of doing the ForEach loop equivalent in JavaScript:
var names = ["Chris", "Kate", "Steve"];
for(var i in names)
{
alert(names[i]);
}
In the above code, the variable i
is our iterator and by using the in
keyword the for
loop actually loops through all elements in the Array for us. Using this you no longer have to worry about the length of the array.
One thing to note about using this to iterate over an array is that it will not necessarily iterate over the array in the order of their index 0 to n. Basically, the order of iteration is not guaranteed.
More Information: https://developer.mozilla.org/en/JavaScript/Reference/Statements/for…in
Related Posts
-
Include Javascript File in Another Javascript File
22 Mar 2024 -
Javascript: How Closures Work
22 Mar 2024 -
Javascript: Redirect to another webpage with Javascript and jQuery
22 Mar 2024 -
Javascript: Check if string contains a substring
21 Mar 2024 -
JavaScript: How to Print to Console, console.log, console.error, console.debug
06 Dec 2023 -
How to Hide a Column in AG-Grid and Prevent it from Displaying in the Tool Panel
11 Oct 2023