Reverse a String - Code works but is not accepted as correct?

var reversedString = ["asdf"];

function reverseString(str) {
  for(var x = str.length; x > -1; x--) {
  var returnedString = reversedString.join("");
  return returnedString;
reverseString("Greetings from Earth");

This works everytime and gives me the correct reversed string of the word, but for some reason freeCodeCamp still marks it as wrong. What am I doing wrong?

It is the global variable reversedString. You should declare an empty array within your function and take out the pop line because it is not needed with a blank array. Why? Because the FCC tests are ran consecutively and reversedString will retain the last value it has at the start of the next test. That is why it is typically recommended to avoid global variables. They can inadvertently be changed by other functions who may use the same variable names as your globally declared variables.

  1. You start the loop at str[str.length] which is one higher than the largest index of the string, so is undefined, so the first value you push is always that.
  2. You use a global variable. So when you run the first time, reversedString becomes [undefined, 'c','b','a']. Next time you run it, say for ‘def’, you pop reversedString so that is [undefined, 'c', 'b'] then you push the new values on so it becomes [undefined, 'c', 'b', undefined, 'f', 'e', 'd'] and so on.