Back to JavaScript
2026-03-016 min read

SyntaxError: a declaration in the head of a for-of loop can't have an initializer

Learn SyntaxError: a declaration in the head of a for-of loop can't have an initializer step by step with clear examples and exercises.

Title: SyntaxError: a declaration in the head of a for-of loop can't have an initializer - JavaScript

Why This Matters

In this tutorial, we will delve into understanding why you might encounter the "SyntaxError: a declaration in the head of a for-of loop can't have an initializer" error while working with JavaScript. By learning about this common pitfall, you'll be better prepared to tackle real-world coding challenges and debug errors more efficiently.

Prerequisites

To fully grasp the concepts discussed in this lesson, you should have a good understanding of:

  1. Basic JavaScript syntax
  2. Control structures such as loops (for, while, do-while)
  3. Variables, constants, and data types
  4. Arrays and objects
  5. ES6 features like template literals, arrow functions, and destructuring assignments
  6. Understanding the difference between for...of loop and traditional for loops
  7. Basic error handling in JavaScript

Core Concept

The for...of loop is a modern and flexible way to iterate over iterable objects like arrays, strings, and even custom objects in JavaScript. It was introduced in ECMAScript 6 (ES6) and provides an easier-to-read alternative to traditional for loops. Here's the basic structure of a for...of loop:

for (const item of iterable) {
// code block to be executed for each iteration
}

In this syntax, item is a variable that represents the current element being iterated over. The iterable is the object you want to loop through. However, there's an important rule to remember: You cannot declare and initialize a variable in the head of a for-of loop.

Example

Let's consider the following incorrect code snippet that will trigger the "SyntaxError: a declaration in the head of a for-of loop can't have an initializer" error:

for (let i = 0, item of [1, 2, 3]) {
console.log(item);
}

In this example, we are trying to declare and initialize the variable i in the head of the for-of loop. This is not allowed, and you should instead use a traditional for loop or rewrite the code as follows:

for (const item of [1, 2, 3]) {
let i = 0; // Move the declaration outside the loop
console.log(item);
}

Proper Use of for...of Loop

The for...of loop is designed to work with objects that have a Symbol.iterator method, which allows JavaScript to iterate over them easily. This includes arrays, strings, and even custom objects. Here's an example using a custom object:

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

for (const item of myObject) {
console.log(item); // This will log the keys of the object (a, b, c)
}

To loop through the values instead, you can use Object.values() or a traditional for loop:

const values = Object.values(myObject);
for (const value of values) {
console.log(value); // This will log the values of the object (1, 2, 3)
}

// Traditional for loop
for (let key in myObject) {
console.log(myObject[key]); // This will log the values of the object (1, 2, 3)
}

Worked Example

Let's walk through a practical example to demonstrate how to use the for...of loop correctly and avoid the "SyntaxError: a declaration in the head of a for-of loop can't have an initializer" error.

Step 1: Create an array

const numbers = [1, 2, 3, 4, 5];

Step 2: Use a traditional for loop to iterate over the array (incorrect)

let sum = 0;
for (let i = 0; i < numbers.length; i++) {
const currentNumber = numbers[i];
console.log(currentNumber);
}

Step 3: Rewrite the code using a for...of loop (correct)

let sum = 0;
for (const currentNumber of numbers) {
sum += currentNumber;
}
console.log(sum);

Or, you can use ES6's arrow function and template literals to make the code even more concise:

const numbers = [1, 2, 3, 4, 5];
let sum = 0;
numbers.forEach((currentNumber) => {
sum += currentNumber;
});
console.log(sum);

Common Mistakes

  1. ### Declaring variables in the head of a for-of loop
for (let i = 0, item of [1, 2, 3]) {
// This will cause a SyntaxError
}

Instead, move the variable declaration outside the loop:

let i;
for (const item of [1, 2, 3]) {
i++;
console.log(item);
}
  1. ### Using a for...of loop with non-iterable objects
const obj = { a: 1, b: 2 };
for (const item of obj) {
// This will cause a TypeError
}

Instead, use the for...in loop or Object.values()/Object.keys() to iterate over objects:

for (const key in obj) {
console.log(obj[key]);
}

const values = Object.values(obj);
for (const value of values) {
console.log(value);
}
  1. ### Misusing the for...of loop with arrays that contain non-objects
const mixedArray = [1, 'two', 3];
for (const item of mixedArray) {
// This will cause a TypeError
}

Instead, use a traditional for loop or check the type of each element:

for (let i = 0; i < mixedArray.length; i++) {
if (typeof mixedArray[i] !== 'object') {
console.log(mixedArray[i]);
}
}

Common Mistakes (Continued)

  1. ### Using for...of loop with objects that have non-enumerable properties
const obj = Object.defineProperties({}, {
a: { value: 1, enumerable: false },
b: { value: 2, enumerable: true }
});

// Using for...of
for (const item of obj) {
console.log(item); // This will not log the non-enumerable property 'a'
}

Instead, use a traditional for...in loop or Object.values()/Object.keys() to iterate over objects:

// Using for...in
for (const key in obj) {
console.log(obj[key]); // This will log both enumerable and non-enumerable properties
}

// Using Object.values()/Object.keys()
const values = Object.values(obj);
console.log(values); // This will log an array containing both enumerable and non-enumerable properties

Practice Questions

  1. Write a for...of loop to iterate over the following array and print each element:
const arr = [4, 7, 2, 9, 5];
  1. Rewrite the following traditional for loop using a for...of loop:
let sum = 0;
for (let i = 0; i < 10; i++) {
sum += i;
}
console.log(sum);
  1. Write a for...of loop to iterate over the following object and print each property-value pair:
const obj = { a: 1, b: 'two', c: 3 };
  1. Given an array of mixed data types, write a for...of loop that separates numbers from strings and stores them in separate arrays:
const mixedData = [1, 'two', 3.5, 'four', 6];
let numbers = [];
let strings = [];

// Your code here

FAQ

Why can't I declare a variable in the head of a for-of loop?

Declaring and initializing a variable in the head of a for...of loop is not allowed because it would interfere with the iteration process. The for...of loop is designed to work with the current element being iterated over, which is represented by the variable declared after the of keyword.

How can I iterate over an object using a for-of loop?

You cannot directly use a for...of loop to iterate over objects in JavaScript. Instead, you should use the for...in loop or Object.values()/Object.keys(). Here's an example:

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

// Using for...in
for (const key in obj) {
console.log(`${key}: ${obj[key]}`);
}

// Using Object.values()
const values = Object.values(obj);
for (const value of values) {
console.log(value);
}

Can I use a for...of loop to iterate over a string?

Yes, you can use a for...of loop to iterate over a string in JavaScript. Each iteration will yield the current character of the string:

const str = 'Hello';
for (const char of str) {
console.log(char);
}

What happens if I try to use a for...of loop with an array that contains non-objects?

If you use a for...of loop with an array that contains non-objects (like numbers or strings), it will work as expected and iterate over each element in the array. However, if you try to access properties of these elements (since they are not objects), you may encounter errors. To avoid this, you can use a traditional for loop or check the type of each element before trying to access its properties:

const mixedArray = [1, 'two', 3];
for (const item of mixedArray) {
if (typeof item === 'object') {
// Access properties of object here
} else {
console.log(item); // Print numbers and strings directly
}
}
SyntaxError: a declaration in the head of a for-of loop can't have an initializer | JavaScript | XQA Learn