Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

65
Views
How do I make a loop for this specific code

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//
7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

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");
}

7 months ago · Juan Pablo Isaza Report

0

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)
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.