Help me understand why it's undefined

Tell us what’s happening:
So I am trying to make a function the takes one argument, a string. And I am trying to make it reverse. So in order to do that I have to convert in into an array. So [h,e,l,l,o] becomes [o,l,l,e,h] and comes out as a string 'olleh'. I managed to convert it into an array. I am trying to test out my method before making a for loop. I tried unshift(a[b]) and b=a.length so it would add the last letter to the front. But its says [undefined, h, e, l, l,o] and I am stuck here, I was gonna use pop() to delete the last letter and make a loop until the array was reversed. Can someone explain why it is undefined?

Your code so far

function reverseString(str) {
let a = []
a = [...str];
const b = a.length; 


return a;


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36.

Challenge: Reverse a String

Link to the challenge:

Arrays are zero indexed, the length is one higher than the last index


Hi @Kazeoni15

as a.length provides the total number of elements in the array.
Also as the array index starts from the zero so the last index will be one less than the total number of element .

so by doing

you are trying to access the element which is not there.

Hope I was able to explain it properly :slightly_smiling_face::slightly_smiling_face:

1 Like

It was helpful. Thank you!

It was helpful. Thank you!!