Categories
JavaScript Answers

How to Fix the ‘SyntaxError: a declaration in the head of a for-of loop can’t have an initializer ‘ Error in Our JavaScript App?

Spread the love

Sometimes, we may run into the ‘SyntaxError: a declaration in the head of a for-of loop can’t have an initializer’ when we’re developing JavaScript apps.

In this article, we’ll look at how to fix the ‘SyntaxError: a declaration in the head of a for-of loop can’t have an initializer’ when we’re developing JavaScript apps.

Fix the ‘SyntaxError: a declaration in the head of a for-of loop can’t have an initializer’ When Developing JavaScript Apps

To fix the ‘SyntaxError: a declaration in the head of a for-of loop can’t have an initializer’ when we’re developing JavaScript apps, we should make sure that we don’t have any assignment statements in the parentheses for the for-of loop.

For instance, instead of writing code like:

const arr = [10, 20, 30];

for (let value = 50 of arr ) {
  console.log(value);
}

where we have an invalid assignment statement in the head of the for-of loop, we write:

let value = 0;

const arr = [10, 20, 30];

for (const value of arr) {
  value += 50;
  console.log(value);
}

where we assign a value to the value variable inside the for-of loop body, which is valid.

If we want to assign a value in the head of the loop, we can use the for loop.

Conclusion

To fix the ‘SyntaxError: a declaration in the head of a for-of loop can’t have an initializer’ when we’re developing JavaScript apps, we should make sure that we don’t have any assignment statements in the parentheses for the for-of loop.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *