Help in basic algo

Tell us what’s happening:
why is my code giving undefined when i console.log it .
also if i get
correct answer it wont pass the test cases . kindly help
Your code so far


let arr = "";
function reverseString(str) {

for(let i=str.length;i>=0;i--){
   arr +=str[i];
} 
return arr;
}


console.log(reverseString("hello"));

Your browser information:

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

Challenge: Reverse a String

Link to the challenge:

let arr = "";
function reverseString(str) {

You’ve got a global variable. The let arr = "" should not be outside the function

What basically happens with that global variable is that the first test runs, passes. arr is now “elloh”. Next test runs, you add more characters on, so you get “ellohydwoH”, test fails, next test runs, add on and so on.

2 Likes

Let’s look at the string ‘hello’.
It has a length of 5.

'hello'[0] // 'h'
'hello'[1] // 'e'
'hello'[2] // 'l'
'hello'[3] // 'l'
'hello'[4] // 'o'
'hello'[5] // undefined
3 Likes

thank you ! that helped

1 Like

yahh i know i fixed it thank you very much for helping

1 Like

Ach, I even chucked a console log in and saw it was printing “undefined” for every test and just ignored it

1 Like

It’s probably the most common gotcha when choosing to count down instead of up in the for loop. Always gets me.

2 Likes