Having a hard time understanding for loops in arrays. Trying to create a Thank You card creator and these are the steps I'm trying to follow:
const names = []
function writeCards(names, event) {
for (let i = 0; i < names.length; i++) {
console.log(`Thank you, ${names[i]} for the wonderful ${event} gift!`);
return names;
}
Not sure if I'm on the right track. Thanks for your help!
You can use Array.push()
function writeCards(names, event) {
let messages = []
for (let i = 0; i < names.length - 1; i++) {
messages.push("Thank you, " + names[i] + " for the wonderful " + event + " gift!")
}
return messages;
}
I know your question is focused on for loop, but just in case, you might be interested in using map to achieve the desired result in a more concise manner:
const names = ["Joe", "Nina"]
function writeCards(names, event) {
return names.map(name=> `Thank you, ${name} for the wonderful ${event} gift!`)
}
console.log(writeCards(names, "birthday"))
well the i had this issue
i had an empty array outside a loop and wanted to update it inside a loop
and finally return an array with alot of indexes
//ie
//let arr = []
//LOOP then runs
//then console.log(arr) //console shows [1,2,3,4,5,6,7]
this is how you do it
let arr = []
let realArray = [1,2,3,4,5]
for (let index = 0; index < realArray.length; index++) {
const element = realArray[index]
arr.push(element)
}
console.log(arr)//your arr = 1,2,3,4,5
this is my first answer here