For loop ReferenceError: 'i' is not defined in JS

avatar

Borislav Hadzhiev

Last updated: Oct 19, 2021

banner

Photo from Unsplash

For loop ReferenceError: 'i' is not defined in JS #

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 that 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 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.

Conclusion #

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.