Reverse a String problem and Solution

Tell us what’s happening:
i used this code for challenge and return the good result but the system not gave don’t see it as a correct Solution i know this Solution is so long and complex that the Solution I thought about first so i ask.

Your code so far


  var arr=[];
function reverseString(str) {

  for(let i=0; i<str.length;i++){
    var a = str.charAt(i);
    arr.unshift(a);
  }
  str="";
  for(let j=0; j<arr.length;j++){
    str +=arr[j];
  }
  return str; 
}
console.log(reverseString("Greetings from Earth"));
reverseString("hello"); 

Link to the challenge:

Hi @silverx :grinning:

delcare and assign var arr=[ ] in reverseString function and here you have two str (one is as parameter in reverseString function and another is str="" so take another str to anything else like str1).

corrections -

  1. shift var arr=[ ] line into function top.
  2. change str=" " to something like str1=" "and also put var keyword like var str1 = " "

so, finally your code -

function reverseString(str) {
  var arr = [];
  for(let i=0; i<str.length;i++){
    var a = str.charAt(i);
    arr.unshift(a);
  }
  var str1="";
  for(let j=0; j<arr.length;j++){
    str1 +=arr[j];
  }
  return str1;
}

console.log(reverseString("Greetings from Earth"));
reverseString("hello");

Note - Try some other ways also, which have less code to write.

Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.

Example:

var myGlobal = [1];
function returnGlobal(arg) {
  myGlobal.push(arg);
  return myGlobal;
} // unreliable - array gets longer each time the function is run

function returnLocal(arg) {
  var myLocal = [1];
  myLocal.push(arg);
  return myLocal;
} // reliable - always returns an array of length 2

hi dev-313 thank you for your reply i understand now.
i know me Solution very long. when i saw the get hint page i was shocked
that the solution was one line and i realized that my solution was stupid,

hi ieahleen
thank you for your reply i now the difference between global and local variables but i didn’t thought that will be a problem in the solution.

take your code, then call the function twice, check what the two functions return, and then check what’s the value of arr, you will see why global variables are the issue