I know the code I'm making is really simple but I have tried to watch so many tutorials and make those code work in my JavaScript code but I just can't seem to understand. Some help as soon as possible would be useful. I'm trying to simplify this code into a loop and it's suppose to ask the user how many is coming to the party and than asking a follow-up question of the names of the guests depending on how many is coming. gjester=guests
var gjester = prompt("How many is coming to your party?");
if (gjester == 1){
var name1 = prompt("What is the name of guest 1?");
console.log("Yey " + name1 + " is coming to your party")
}
if (gjester == 2){
var name1 = prompt("What is the name of guest 1?");
var name2 = prompt("What is the name of guest 2?");
console.log("Yey " + name1 + " is coming to your party");
console.log("Yey " + name2 + " is coming to your party")
}
//and so on//
This can be solved using a simple for loop
let gjester = prompt("How many is coming to your party?");
let names = []
for(let i = 0; i<gjester ; i++) {
names.push(prompt(`What is the name of guest ${i+1}?`))
console.log("Yey " + names[i] + " is coming to your party");
}
You can use a do/while loop like so:
var count = prompt("How many is coming to your party?");
var names = []
do {
let name = prompt("What is the name of guest " + count + "?");
names.push(name);
count--
} while (count > 0)