Where is undefined coming from? I thought I initialised the string correctly. (tried using debugger but can’t figure out the issue)
I’ve tried using concat()
method. I’ve tried +=. Everything results in "undefined"
Why?
const reverseString = function(string) {
let newWord = "";
for (i = string.length; i > -1; i--) {
newWord = newWord.concat(string[i]);
}
return newWord
};
Edit: in case it’s unclear when running console.log(reverseString("Hello"))
expected output would be "olleH"
actual output is "undefinedolleH"
2
Answers
As @VLAZ mentioned in the comment, your string.length is more than the actual length of the string that’s why it bounces out of the array.
There are ways you can get rid of the undefined on your string. One is what VLAZ said which is just to -1 the length. The other one is using a Nullish Coalescing Operator on your concatenation. Samples below
Index should start with (n-1), not from n