I can not figure out why I do get “undefined” output in console log
Down below you can see my code that is trying to reverse a string. But unfortunately, I do not know why I do get “undefined” in the console log instead of every letter. I guess the logic should be correct but I am not 100% confident about it.
**This is my code so far**
function reverseString(str) {
var string = str;
var newString = "";
for (let i = 0; i < string.length; i++) {
newString += string[-1 + (-i)];
}
str = newString;
return str;
}
reverseString("hello");
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36
Thank you for you answer. I am used to calling last character of a string with index “-1” from Python and also the later ones “-2” (second to last character and so on), … . This does not work in javascript?
unfortunately JS is not so flexible in that department. index -1 is considered non existant. If you try [1,2,3,4].indexOf(5) it will return -1. Like other people pointed out, you can use a more old fashined approach and count string chars from back to front(starting from last char index and decrement the number as the loop goes)
By your way, the line in for loop should be newString += string[string.length - 1 - i]
changing the index to the last index and decreasing for each character of the string
Bracket notation is how you access object properties. There isn’t a key “-1”, so myArray[-1] is undefined. It doesn’t do anything clever here, it’s just a basic object lookup.
Just as an FYI, at, which is not available yet but is likely to be in the language next year (and afaics has buy-in from every browser so should roll out everywhere very quickly one it’s approved, + is extremely easy to polyfill for browsers that don’t support it) lets you do what you’re looking for – myArray.at(-1) will do exactly what you’re expecting.