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