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");
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?)
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.
@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.
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;
}