Assessment wanted: functions 3

Hi everyone. I will really appreciate your feedback on the answer I have provided to this assessment.

Here’s my solution for functions 3: https://codepen.io/coddysey/pen/pogZYpM

Here’s the assessment: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Test_your_skills:_Functions

Reading your source code, I believe that it will sometimes print undefined instead of a first name. Am I wrong?

Thanks @yoric. I tested it several times and never got such result. Where do you think the bug might be?

If you look at random(min, max), you can determine that the result can be any value between min (included) and max (included).

Consequently, random(0, names.length) can be any value between 0 (included) and names.length (included).

Now, names[0] is 'Chris'. But what is names[names.length]?

names.length is the length of the array which is in this case the last item in the array would therefore return a value of ‘jada’

Are you sure?

To check this out, you could open the DevTools, go to the console and write

let names = ['Chris', 'Li Kang', 'Anne', 'Francesca', 'Mustafa', 'Tina', 'Bert', 'Jada'];
names[names.length]

I agree with Yoric, console.log(names[names.length-1]); will give the right result.

Oooops. Thanks a bunch, I will fix the code

thanks for the feedback

1 Like

Hey guys, I was having trouble with this task, so came here for help. seeing this brought up another question of why is the -1 required in names[names.length-1].
and tested and see that it does work, but why cant you just set names.length??

thanks for any replies, I am eager to understand :slight_smile:

using the example below in your console:

let names = ['Chris', 'Li Kang', 'Anne', 'Francesca', 'Mustafa', 'Tina', 'Bert', 'Jada'];
console.log(names.length) // 8.

Remember that arrays are initiated from zero i.e
index0 - Chris;
index1 - Li Kang;
index2 - Anne;
index3 - Francesca;
index4 - Mustafa;
index5 - Tina;
index6 - Bert;
index7 - Jada

The index of the last character in the array equals 7. This means that the length of the array is always 1 more than the last character of the array. So, if I typed
console.log(names[names.length])//undefined because there is no 8th character in the array. If I typed
console.log(names[names.length -1])//Jada
it would return the last character.

I hope this help you understand.

hey so, if im understanding this right

names[names.length] does not take into account that the index starts at 0?

so we need to adjust the length we want searched to take that into account?

sorry, I just thought that the length method would already take that it starts from 0 it into account since there are 8 items in the Array.

Thank you for your reply :slight_smile: