Solve - For loop ReferenceError 'i' is not defined in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - For loop ReferenceError 'i' is not defined #

The "ReferenceError: i is not defined" error occurs when we forget to use the let statement to define the index variable in a for loop. To solve the error, use the let statement to declare the variable in the loop.

referenceeeror i is not defined

Here's an example of how the error is caused.

index.js
const arr = ['a', 'b', 'c']; // โ›”๏ธ ReferenceError: i is not defined for (i = 0; i < arr.length; i++) { console.log(arr[i]); }

Notice that we did not declare the i variable in the for loop.

To solve the error, we have to use the let statement to declare the variable in the for loop.

index.js
const arr = ['a', 'b', 'c']; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); // ๐Ÿ‘‰๏ธ a, b, c }

We used the let statement to declare the i variable in the loop.

The let statement allows us to declare a variable which is block scoped (it's only available in the for loop).

Variables declared using let can also be reassigned, as opposed to variables declared using const.

Don't try to declare the i variable in a loop using the const statement.

index.js
const arr = ['a', 'b', 'c']; // โ›”๏ธ Assignment to constant variable for (const i = 0; i < arr.length; i++) { console.log(arr[i]); // ๐Ÿ‘‰๏ธ a, b, c }

When we try to reassign the value for the i variable on the second iteration, we get the "Assignment to constant variable" error, because constants cannot be reassigned.

In older code snippets you might see the var statement being used to declare the variable in a loop.

index.js
const arr = ['a', 'b', 'c']; for (var i = 0; i < arr.length; i++) { console.log(arr[i]); // ๐Ÿ‘‰๏ธ a, b, c }

This also works, but it's not a good practice, because the variable we declared using var is not block scoped. We can access it even outside of the for loop.

index.js
const arr = ['a', 'b', 'c']; for (var i = 0; i < arr.length; i++) { console.log(arr[i]); // ๐Ÿ‘‰๏ธ a, b, c } console.log(i); // ๐Ÿ‘‰๏ธ 3

Polluting the upper scope for no reason is a bad practice, so you should be using the let keyword to declare variables in a for loop.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee