Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

120
Views
I want to loop a prompt and save each loop in an array

I am new to javascript and I want to create a program that loops a prompt(input) but to a limit specifically four times and saves each looped prompt to an array. This is my code

const fruits = [];
var ask = prompt('Enter a fruit');
for(let num = 0; num < 5; num++){
fruits.push(ask); } console.log(fruits);

const fruits = [];

var ask = prompt('Enter a fruit');

for(let num = 0; num < 5; num++){
    fruits.push(ask);   
}
console.log(fruits);

But this is the result [ "Banana", "Banana", "Banana", "Banana", "Banana" ]

It only asks for the input once and saves it in the array five times, any ideas?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Move prompt inside the loop so that you ask question each time.

const fruits = [];

for(let num = 0; num < 5; num++){
    var ask = prompt('Enter a fruit');
    fruits.push(ask);   
}
console.log(fruits);

about 4 years ago · Juan Pablo Isaza Report

0

The prompt is responsible for taking input and need to be shown 4 time, so it should also be inside the loop

const fruits = [];

   

for(let num = 0; num < 5; num++){
    var ask = prompt('Enter a fruit'); // put here
    fruits.push(ask);   
}
console.log(fruits);

about 4 years ago · Juan Pablo Isaza Report

0

prompt should be inside the loop and if you want to loop 4 times then for loop should look like this. try this.

const fruits = [];

for(var num = 0; num < 4; num++){
    fruits.push(prompt('Enter a fruit')); 
} 

console.log(fruits);

about 4 years 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 vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!