U. Essien
U. Essien

Reputation: 1

prompt only loops once

I'm learning javascript. I was trying to make a loop that keeps prompting the user for activities which then gets stored in an array. If the user inputs 'DONE' it stops asking for inputs.

The problem is, after it runs once, the loop ends even though the while condition isn't met.

I am using jsbin as a sandbox to practice js. Here is the code:

var todoList = [];
while (input != "DONE") {
var input = prompt("Please enter an activity. When you are done type 'DONE'.");
todoList.push(input);
}

Thanks

Upvotes: 0

Views: 834

Answers (4)

RanjithKumar SV
RanjithKumar SV

Reputation: 225

We should able to handle upper and lowercase letters.

var res, input = "";
var todoList  = [];
while (res !== "DONE") {
 if (input != "" && input != null) {
   todoList.push(input);
 }
  input = prompt("Please enter an activity. When you are done type 'DONE'.");
  if (input !== null) {
   res = input.toUpperCase();
  }
}
console.log(todoList);

jsfiddle

Upvotes: 0

Mohamed Sahir
Mohamed Sahir

Reputation: 2543

@Afixoftrix your code is working fine in browser console and js fiddle .JsBin have some protection for infinite loop.see it in console.if you need to study javascript,dont learn it in thirdparty tool,use code editor or browser console which help to get more knowledge about javascript.enter image description here

See more:JS Bin while infinite loop

Js fiddle consolelog:enter image description here

Upvotes: 0

clearshot66
clearshot66

Reputation: 2302

Var needs to be outside the loop.

var input;
var todoList = [];
while (input != "DONE") {
     input = prompt("Please enter an activity. When you are done type 'DONE'.");
     todoList.push(input);
}

Upvotes: 1

Ben Kolya Mansley
Ben Kolya Mansley

Reputation: 1793

Your input variable is only inside your loop. Initialise it, before the loop with var input = "";.

Then remove var from the loop (as you're assigning a value to the existing variable), it should work ok.

var todoList = [];
var input = "";
while (input != "DONE") {
  input = prompt("Please enter an activity. When you are done type 'DONE'.");
  todoList.push(input);
}

Upvotes: 1

Related Questions