You start the loop from userInput.length
which is a wrong index because userInput[userInput.length]
is undefined
. What you need to do is start from userInput.length - 1
like this (and don't forget to initialize result
to empty string before starting to accumulate the result):
result = "";
for (var i = userInput.length - 1; i >= 0; i--) {
result += userInput[i];
}
NOTE: When going up an array, we don't actually reach the point when we access the userInput.length
index (i.e. userInput[userInput.length]
) because usually the condition for the loop is i < userInput.length
which fail as soon as i
is equal to userInput.length
. When going downwards an array, one should keep track of what are the indexes allowed.
NOTE 2: It is safer to use string.charAt(index)
rather than string[index]
. Learn why here.