1

I'm new to programming and for the moment I'm learning JavaScript using a combination of online courses. One challenge I'm working on is to use a function to return a random string from an array. That part itself was easy, but it seems like I need to be able to create the array from the input I give when I call the function. As an example, if I were to create a function like this:

function namePicker(names);

And I then called the function and gave it this input:

namePicker("Billy","Timmy","Johnny");

then I should be able to use the input to create an array of these names. However, when I tried to work this into the code for the random name picker, only the first name I gave would return to me.

What am I doing wrong here? Here's the full code I've been working on:

function lunchClubLottery(names) {
    var lunchClub = [names];    
    var randomNumber=Math.floor(Math.random()*lunchClub.length);
    return lunchClub[randomNumber];
}
mr_fenroe
  • 11
  • 1
  • 1
    Does this answer your question? [Is it possible to send a variable number of arguments to a JavaScript function?](https://stackoverflow.com/questions/1959040/is-it-possible-to-send-a-variable-number-of-arguments-to-a-javascript-function) – UnholySheep Feb 22 '20 at 22:48
  • It did, but not on its own. I didn't understand what they were talking about until I read Ben's answer as well. Thank you for the link anyway. – mr_fenroe Feb 22 '20 at 23:07

1 Answers1

1

The rest parameter syntax (...) can be used to create an array of all (or some of) the arguments supplied to a function.

function lunchClubLottery(...names) {
    var i = Math.floor(Math.random()*names.length)
    return names[i]
}

const name = lunchClubLottery("Billy","Timmy","Johnny")

console.log(name)

Or if you want to go old-school, you can use the arguments object (if you are not using a fat arrow function).

Here I convert the array-like arguments object to an Array using slice and call.

function lunchClubLottery() {
    const names = Array.prototype.slice.call(arguments)
    var i = Math.floor(Math.random()*names.length)
    return names[i]
}

const name = lunchClubLottery("Billy","Timmy","Johnny")

console.log(name)
Ben Aston
  • 53,718
  • 65
  • 205
  • 331