Need Help! Reverse a string challenge

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--) {
  if (i === 0) {
    return reverse.join("");

reverseString("Greetings from earth");

FCC checker doesn’t like global variables

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?)

Try this:

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


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.

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.

function reverseString(str) {
  var sort = [];
  sort = str.split('');
  return sort;

1 Like

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.

@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.


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


why can’t you do

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

return sort;???

another question,

How do you enclose code in the dark portion?

I was told triple ///.

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”);