Reputation: 525
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.
Upvotes: 0
Views: 886
Reputation: 1178
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);
}
Upvotes: 2