Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing an array as a parameter to a function to pick a random string

I am currently doing a javascript course on udemy and ran into a problem with a small coding challenge. The code is supposed to pick a random person from an array. My code works on their test platform, but i cant get it to work in the chrome developer tools.

var names = ["Angela", "Ben", "Jenny", "Michael", "Chloe"];
 
function whosPaying(names) {
    var randomNumber = Math.random();
    var arrayLength = names.length;
    var hasToPay = Math.floor((arrayLength * randomNumber));
 
    return names[hasToPay] + " is going to buy lunch today!"
}
 
whosPaying();

If i write my code like this, it works in the test environment when I submit the code without the array "names", but in chrome I get the following error:

index.js:5 Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at whosPaying (VM165 index.js:5)
    at VM165 index.js:11

If i define the array inside the function, it works, but that is not really what I’m supposed to do.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Im wondering how i can make the function use the array that is defined outside of the function. In the exercise instructions the array and the way it is passed on to the function are predefined exactly the same way i did it.

I could not find a solution to this that does not include completely different syntax or stuff I am not yet supposed to know at this point in the course.

>Solution :

you’ve called whosPaying without any args, then names end up being undefined.

Do this instead: whosPaying(names), or drop the names parameter of whosPaying

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading