JavaScript For loop - the tutorial has 4 mistakes

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);
}
  1. the variable is never reassigned, it needs to be const instead of let
  2. name is a reserved word and must not be used for naming variables
  3. the loop is made with <=, that way 4 elements of the 3 will be printed (1 undefined)
  4. 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.

It is a best practice to use const in this case but it isn’t required and thus doesn’t “need” to use const.

Did you test this to make sure that is the case? Because I think you might be surprised by what you find :slight_smile:

Your last two points are valid though.

Yes it is deprecated but my vim linter puts a blank line through the word.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.