Reversing string

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;

  **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

Challenge: Reverse a String

Link to the challenge:

So do this in paper:

If i is 0, what is -1 + -0
If i is 1, what is -1 + -1

And so on

You can loop in any direction you know, you don’t have to start from zero and use ++.

It is most likely the logic :slight_smile:
For example: accessing the last character of a string looks like this

const str = "carrots"
const lastCharOfStr = str[str.length - 1]
console.log(lastCharOfStr)  //--> s

You tried to do it bit differently.

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

Yeah, doesn’t work like Python.

Arrays are basically just JS objects. There are a few special properties unique to arrays but on the whole you can think of

myArray = [10,20,30]


myArray = { "0": 10, "1": 20, "2": 30, length: 3 }

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 – will do exactly what you’re expecting.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.