Reverse A String -code check

I’m on the Basic Algorithm Structures part of the JavaScript course and I’m on the reverse a string challenge. I don’t know why the below code won’t work.


function reverseString(str) {
let rev = Array.from(str);
var myArray = [];
for (let i = rev.length; i > 0; i--){
  myArray.push(rev[i]);

}
let done = toString(myArray);

return done;
}

reverseString("hello");
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36 Edg/95.0.1020.44

Challenge: Reverse a String

Link to the challenge:

The first thing I would try to do is to try to figure out where it is not doing what you want. I would do something like this:

function reverseString(str) {
  let rev = Array.from(str);
  console.log('rev', rev)
  var myArray = [];
  for (let i = rev.length; i > 0; i--){
    myArray.push(rev[i]);

  }
  console.log('myArray', myArray)
  let done = toString(myArray);
  console.log('done', done)
  return done; 
}

console.log('returned', reverseString("hello"));

See if you can figure it out with that. A big part of being a developer is being a good detective.

I would also suggest looking up some standard JS prototype methods, like split and join. Google “mdn array split”.

Work with those and check back if you’re still stuck.

Thanks that was so helpful. I must keep that tip in mind about using the console.log more. It will keep me from working in the dark. That tip on using join brought it all together.

Solution below:

function reverseString(str) {
let rev = Array.from(str);

var myArray = ;
for (let i = rev.length-1; i >= 0; i–){
myArray.push(rev[i]);

}
let done = myArray.join("")

return done;
}

reverseString(“hello”);

And as I was trying to hint, the split method would be a more common method to break a string into an array. In fact, if you look on that MDN list of prototype arrays, you’ll find a third method that (combined with the other two, chained together), could have made this a one-line solution. Not that one-liners are always better, but it is an option here.

Yes I did see that and I know for next time. There are definitely more elegant solutions to the problem but I suppose it was just a little bit of beginner’s pride to see if my limited knowledge and reasoning could solve the issue.

Thank you for the tips!!

Yes, absolutely, I didn’t mean to diminish your accomplishment. In fact, the way you solved it was more interesting and instructive than just using the prototype methods. But they do come in handy and it’s good to know them. It’s also good to get into the habit of checking documentation like the MDN site.

Good work, have fun on the next one.