1
\$\begingroup\$

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Billal Begueradj Oct 1 '17 at 16:37
3
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ +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. \$\endgroup\$ – Przemek Oct 1 '17 at 20:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.