0

I am trying to create a for loop to iterate through an array called "synonyms"; then I want to push a greeting string with the format "Have a [synonym] day!" into a new "greetings" array.

I encounter the following error when executing my code: Reference Error on line 7: i is not defined

const synonyms = ['fantastic', 'wonderful', 'great'];
const greetings = [];

// 1.
// Loop through the synonyms array. Each time, push a string into the greetings array. 
// The string should have the format 'Have a [synonym] day!'
for (i = 0; i < synonyms.length; i++) {
  let newString = "Have a "+ synonyms[i] + " day!";
  greetings.push(newString);
}

I think the for loop is set up correctly. What's causing my error and any other suggestions to refactor would be greatly appreciated.

Codestudio
  • 525
  • 3
  • 5
  • 28

1 Answers1

2

Your initialization step in the for loop is missing the let keyword when declaring the variable

const synonyms = ['fantastic', 'wonderful', 'great'];
const greetings = [];

// 1.
// Loop through the synonyms array. Each time, push a string into the greetings array. 
// The string should have the format 'Have a [synonym] day!'
for (let i = 0; i < synonyms.length; i++) {
  let newString = "Have a "+ synonyms[i] + " day!";
  greetings.push(newString);
}
Uzair Ashraf
  • 1,171
  • 8
  • 20