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];
}
2

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your explanation, it really helped me out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.