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

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:

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output:

10
20
30

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

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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>

chevron_right


Output(in console):

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

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.