Yesterday there was a tutorial about looping through arrays in JavaScript published on the news site:
https://www.freecodecamp.org/news/how-to-loop-through-an-array-with-for-loop-in-javascript/
This is the final code:
let name = ['Dennis', 'Precious', 'Evelyn']
for (let i = 0; i <= name.length; i++)
{
console.log(name);
}
- the variable is never reassigned, it needs to be const instead of let
- name is a reserved word and must not be used for naming variables
- the loop is made with <=, that way 4 elements of the 3 will be printed (1 undefined)
- the log function doesn’t contain the variable of the loop inside the array, this way not one element but the whole array will be printed out multiple times.
The code should be:
const arrayName = ['Dennis', 'Precious', 'Evelyn']
for (let i = 0; i < arrayName.length; i++) {
console.log(arrayName[i]);
}
Thanks for reading.