Need Help! Reverse a string challenge

Need Help! Reverse a string challenge
0

#1

I wrote my own code, but my solution isn’t being accepted, even though I believe it is returning the correct string every time. Can someone tell me why my code doesn’t pass?

Here is the challenge:

Reverse the provided string.

You may need to turn the string into an array before you can reverse it.

Your result must be a string.

reverseString(“hello”) should return a string.
reverseString(“hello”) should become “olleh”.
reverseString(“Howdy”) should become “ydwoH”.
reverseString(“Greetings from Earth”) should return “htraE morf sgniteerG”.

Here is my code:

var reverse = [];
var reverseString = function(str) {
for (var i = str.length-1; i > -1; i--) {
  reverse.push(str[i]);
  if (i === 0) {
    reverse.toString();
    return reverse.join("");
  }
}
};

reverseString("Greetings from earth");


#2

FCC checker doesn’t like global variables


#3

yeah. Like the other poster said, I would just suggest declaring “reverse” within the scope of the reverseString function. (I just checked and that works for me. if that doesn’t work for you, maybe it is a browser issue?)


#4

Try this:

function reverseString(str) {
return str.split(’’).reverse().join(’’);
}

reverseString(“hello”);


#5

They instructed to use split, reverse, join method, but you only used join method thats why your code is not passed even it gives the result right.


#6

No, they recommend to look into those functions. You can use whatever function you like.

Tests are not passing because the code uses global variable. FreeCodeCamp checker doesn’t reset global variables between tests, that’s why only first test pases.


#7
function reverseString(str) {
  
  var sort = [];
  sort = str.split('');
  sort.reverse();
  sort=sort.join('');
  
  return sort;
}

reverseString("hello");

#8

why must I split the string to reverse it and then join it? Thats not the same as just reversing the string? I don’t get it.


#9

@bjones2nd it’s because .reverse() can reverse the order of an array but not a string. So you have to split the string first and create an array, reverse the array and then join it back together again into a new string.


#10

Thanks! i didn’t know that…That makes sense.


#11

question,

why can’t you do

var sort = [];
sort = str.split(’);
sort.reverse();
sort.join(’’);

return sort;???


#12

another question,

How do you enclose code in the dark portion?

I was told triple ///.


#13

I didn’t found any problem with this code, testing it in the browser. I did it like this:
function reverseString(str) {
var splStr = [];
splStr = str.split(’’);
var revStr = splStr.reverse();
var joinStr = revStr.join(’’);
return joinStr;
}

reverseString(“Greetings from Earth”);


#15