# Random winner selector

I am looking to improve and simplify the way I code. What is the best way to represent this:

let names = [];
let name;

while(true) {
name = prompt('Enter a name:');
names.push(name);

if(name === ''){
names.pop();
break;
}
}

let winner = function(){
return names[Math.floor(Math.random() * names.length)];
}

console.log(winner());

• Please modify your question's title and EXPLAIN what you are trying to achieve. Running the code is annoying and that is an other reason why explanation is needed. – Billal Begueradj Oct 1 '17 at 16:37

There is not much to be done about the random selector. However, I would make the function accept an explicit parameter.

That input loop, though, is too complicated. It also fails to handle the "Cancel" button in any way.

function winner(names) {
return names[Math.floor(Math.random() * names.length)];
}

let names = [];
for (let name; name = prompt('Enter a name:'); ) {
names.push(name);
}
console.log(winner(names));

• +1, but if we are already using ES2015 (because there is let names), we could use arrow syntax to give a little brevity to winner() function. Also, array names should be declared as const, because it's never reassigned. – Przemek Oct 1 '17 at 20:30