I’m working on Active learning: Filling in a guest list in the JavaScript building blocks > Looping Code tutorial: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Looping_code#active_learning_filling_in_a_guest_list.
I have questions regarding some half-written code I’m working on. It’s not working, and I’d love some feedback on the specific reasons why.
I looked at someone else’s answer, and they used a completely different solution–a for loop instead of a for…of loop.
- So my first question is: is a for…of loop just the wrong tool for this task? With the follow up, what are some types of tasks a for…of loop would be good for?
- I don’t think I’m doing the if statement correctly. I think I can’t say “if (people[4])” (see below). I think I have to do something to people[4] or define it or something. I’m trying to say, “when looping through the array, if you’ve landed on the 4th entry, please do this thing.” I’ve changed it to read “(if people[4] === true)”, but this doesn’t provide satisfactory results either.
Here is my code so far:
const people = [‘Chris’, ‘Anne’, ‘Colin’, ‘Terri’, ‘Phil’, ‘Lola’, ‘Sam’, ‘Kay’, ‘Bruce’];
const admitted = document.querySelector(’.admitted’);
const refused = document.querySelector(’.refused’);
admitted.textContent = 'Admit: ';
refused.textContent = 'Refuse: ';
for (person of people) {
if (people[4]){
refused.textContent +=${people[4]},
;
}
else if (people[5]){
refused.textContent +=${people[5]}
;
}
else{
admitted.textContent += ${person},
;
}
}
Any responses are appreciated! I’m not exactly looking for the right answer–I plan to work on trying again with a for loop. I’m specifically looking for thoughts on why what I wrote above doesn’t work, and how to express what I’m trying to do correctly.