Iteration
for statement
Using a for statement like this will generally give you good performance.
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
This example shows how to start from the end of the array and go in reverse.
for (let i = myArray.length - 1; i >= 0; i--) {
console.log(myArray[i]);
}
This example shows how to break out of and discontinue iteration when a condition is met.
let result = false;
for (const item of myArray) {
if (item.length > 3) {
result = true;
break;
}
}
HTMLFormControlsCollection
Here is an example of how we can iterate through a forms inputs when submitted.
HTML Form
<form id="myform">
<input type="text" name="firstname" />
<input type="text" name="lastname" />
<input type="text" name="title" />
<button type="submit">Submit</button>
</form>
Javascript
const myform = document.getElementById("myform");
myform.addEventListener('submit', (evt) => {
evt.preventDefault();
Array.prototype.map.call(evt.target.elements, (el, index) => {
console.log(el.name, el.value, index);
});
}