Skip to content
Related Articles

Related Articles

Improve Article

JavaScript SyntaxError – A declaration in the head of a for-of loop can’t have an initializer

  • Last Updated : 31 Jul, 2020

This JavaScript exception a declaration in the head of a for-of loop can’t have an initializer occurs if the for -of loop contains an initialization expression like |for (var i = 0 of iterable)|. This is not valid initialization in for-of loops.

Message:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

SyntaxError: for-of loop head declarations cannot have 
             an initializer (Edge)
SyntaxError: a declaration in the head of a for-of loop
             can't have an initializer (Firefox)
SyntaxError: for-of loop variable declaration may not have 
             an initializer. (Chrome)

Error Type:

SyntaxError

Cause of Error: The loop contains an initialization that is invalid inside for-of loops.



Example 1:

HTML




<!DOCTYPE html>
<html>
<head>
    <title>Syntax Error</title>
</head>
<body>
    <script>
        let iter = [10, 20, 30]; 
        for (let val of iter) { 
          document.write(val + "<br>"); 
        
    </script>
</body>
</html>

Output:

10
20
30

Example 2: This example contains an invalid initialization inside the head of for-of the loop.

HTML




<!DOCTYPE html>
<html>
<head>
    <title>Syntax Error</title>
</head>
<body>
    <script>
        let iter = [10, 20, 30]; 
        for (let val = 10 of iter) { 
              document.write(val + "<br>"); 
        
    </script>
</body>
</html>

Output(in console):

SyntaxError: for-of loop variable declaration may not have 
an initializer.



My Personal Notes arrow_drop_up
Recommended Articles
Page :