0

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?

1
  • 3
    You can just put the prompt call inside the loop. Commented Oct 28, 2021 at 12:31

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

But it's not inside the loop in your response.
@GhassenLouhaichi left by mistake
1

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

Comments

0

If you want to make it a one-liner (or just prefer a functional approach) you can do this:

const fruits = [1,2,3,4,5].map(() => prompt('Enter a fruit'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.