Categories
JavaScript Answers

How to Fix the ‘SyntaxError: for-in loop head declarations may not have initializers ‘ Error in Our JavaScript App?

Spread the love

Sometimes, we may run into the ‘SyntaxError: for-in loop head declarations may not have initializers’ when we’re developing JavaScript apps.

In this article, we’ll look at how to fix the ‘SyntaxError: for-in loop head declarations may not have initializers’ when we’re developing JavaScript apps.

Fix the ‘SyntaxError: for-in loop head declarations may not have initializers’ When Developing JavaScript Apps

To fix the ‘SyntaxError: for-in loop head declarations may not have initializers’ when we’re developing JavaScript apps, we should make sure that we don’t have variable assignment statements in the head of the for-in loop.

On Edge, the error message for this error is SyntaxError: for-in loop head declarations cannot have an initializer.

On Firefox, the error message for this error is SyntaxError: for-in loop head declarations may not have initializers.

And on Chrome, the error message for this error is SyntaxError: for-in loop variable declaration may not have an initializer..

For instance, we can’t write:

"use strict";

const obj = {
  a: 1,
  b: 2,
  c: 3
};

for (const i = 0 in obj) {
  console.log(obj[i]);
}

since we’re assigning a value in the head of the for-in loop, which is invalid syntax.

Instead, we write:

"use strict";

const obj = { a: 1, b: 2, c: 3 };

for (let i in obj) {
  i = 0;
  console.log(obj[i]);
}

which is valid syntax.

We can also use a regular for loop if we want to assign variables in the head of the loop.

Conclusion

To fix the ‘SyntaxError: for-in loop head declarations may not have initializers’ when we’re developing JavaScript apps, we should make sure that we don’t have variable assignment statements in the head of the for-in loop.

We can also use a regular for loop if we want to assign variables in the head of the loop.

On Edge, the error message for this error is SyntaxError: for-in loop head declarations cannot have an initializer.

On Firefox, the error message for this error is SyntaxError: for-in loop head declarations may not have initializers.

And on Chrome, the error message for this error is SyntaxError: for-in loop variable declaration may not have an initializer..

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 *