-2
 var a = "gsdgtrshghf";
    function reverseString(strr){
       if (!strr.length){
          var result="";
          for(var i=strr.length;i>0;i++){
              var a=strr.chatAt(i);
              result+=a;
          }
       }return result;
   }
console.log(reverseString(a))

When I tried to run it it returned me "undefined". I wonder what's the problem here.

Abhijit Kar ツ
  • 1,732
  • 1
  • 11
  • 24
Xinyi Li
  • 123
  • 1
  • 2
  • 8
  • 2
    you have a typo, `charAt` not `chatAt`. You can also simply use `strr[i]` to get the char. Also, you should do `i--` and `i >= 0` if you start at `strr.length`, otherwise for loop is immediately completed at the condition check – Kevin Qian Mar 17 '18 at 19:48
  • The `if` logic is backwards also. Doesn't make sense to parse the string if it has no length and when it has length then `result` is undefined – charlietfl Mar 17 '18 at 19:51
  • So stupid questionsss! Ignore me plz. THANKS FOR ALL THE HELP – Xinyi Li Mar 17 '18 at 19:57
  • You said you got error when you were trying to remove duplicates in the string, but your code is about reversing the string! – Abhijit Kar ツ Mar 17 '18 at 20:01
  • 1
    a full answer on how reverse a string is [here](https://stackoverflow.com/questions/958908/how-do-you-reverse-a-string-in-place-in-javascript) – gaetanoM Mar 17 '18 at 20:02

2 Answers2

0

Have a look:

var a = "gsdgtrshghf";

function reverseString(strr) {
  var result = "";

  if (strr.length != null) {
    for (var i = strr.length - 1; i >= 0; i--) {
      var a = strr.charAt(i);
      result += a;
    }
  }
  return result;
}
console.log(reverseString(a));

// Better
const reverse = str => Array.from(str).reverse().join('');

console.log(reverse('foo  bar mañana mañana'));

Explanation

  1. It's charAt(i) not chatAt(i)
  2. Loop should start from length - 1 and end at 0 and i should be decremented
  3. And finally declare the variable outside of if

i.e for(var i = strr.length - ; i >= 0; i--){ not for(var i=strr.length;i>0;i++){

  1. Better yet, use combo of Array.from(str).reverse().join(''), as it even works with Unicode characters, as pointed out in comments by gaetanoM
Abhijit Kar ツ
  • 1,732
  • 1
  • 11
  • 24
0

The main reason is you are declaring var result="" and returning from outside of if(so it become undefined as its scope is only inside if statement) and other errors areas mention in comments you have a typo, charAt not chatAt. You can also simply use strr[i] to get the char. Also, you should do i-- and i >= 0 if you start at strr.length, otherwise for loop is immediately completed at the condition check. Check the below code.

var a = "gsdgtrshghf";
    function reverseString(strr){
       var result="";
       if (strr.length){
          
          for(var i=strr.length-1;i>=0;i--){
              var a=strr.charAt(i);
              result+=a;
          }
       }
       return result;
   }
console.log(reverseString(a))
yajiv
  • 2,901
  • 2
  • 15
  • 25