Array give return reverse string?why undefined?

hello new to java script am trying to return a reverse string from a given array am getting the correct result but with undefined keyword …here is the code

let myname=["e","m","u","K"];
function returnName(givenArry){
  let MyNameIs="";
  for(let i=givenArry.length;i>=0;i--){
    MyNameIs+=givenArry[i];
  }
  return MyNameIs;
}
console.log(returnName(myname));

when i debug at visual studio code am getting result
undefinedKume
where did i make undefined variable…

Your loop will run i-- if i >= 0. So if its equal to zero it will remove one, meaning it will try and take from index -1 which is outside the array, resulting in undefined.

If you ran this in lets say C# the program would crash with an IndexOutOfBounds exception.

1 Like

i >= 0 is a reasonable condition when iterating through an array backwards with a for-loop. The problem is that they started with givenArray.length as the initial value for i (which is out of bounds)

1 Like

yap…thanks problem solved givenArray.length is out of bounds it must be givenArray.length-1 …i look other way but it was so simple
let myname=[“e”,“m”,“u”,“K”];
function returnName(givenArry){
let MyNameIs="";
for(let i=givenArry.length-1;i>=0;i–){
MyNameIs+=givenArry[i];
}
return MyNameIs;
}
console.log(returnName(myname));

1 Like