[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Errors/Invalid_for-of_initializer [Back]  [Original]

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

Cette page a t traduite partir de l'anglais par la communaut. Vous pouvez contribuer en rejoignant la communaut francophone sur MDN Web Docs.

View in English Always switch to English

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

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)

Dans cet article

Type d'erreur

SyntaxError

Quel est le problme ?

L'en-tte d'une boucle for...of contient une expression d'initialisation, c'est--dire qu'une variable est dclare et qu'on lui affecte une valeur. Ceci n'est pas autoris pour les boucles for-of. En revanche, les boucles for permettent d'avoir un initialisateur.

Exemples

Boucles for-of invalides

js
let iterable = [10, 20, 30];

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

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

Boucles for-of valides

Il faut retirer l'initialisateur de l'en-tte de la boucle pour ne plus avoir l'erreur. Si cette valeur devait servir d'incrment, on peut ajouter l'addition dans le corps de la boucle.

js
let iterable = [10, 20, 30];

for (let value of iterable) {
  value += 50;
  console.log(value);
}
// 60
// 70
// 80

Voir aussi


Web Proxy Viewer  |  New URL  |  Original Page