0

What is wrong with the following code

function FirstReverse(str) { 
  var backwards = "";
  for(var i = str.length; i>=0;i--){
     backwards += str[i];
      }
  str = backwards;  
  return str; 

}

// keep this function call here 
// to see how to enter arguments in JavaScript scroll down
FirstReverse(readline(str)); 

this is the first challenge on http://coderbyte.com/CodingArea/GuestEditor.php?ct=First%20Reverse&lan=JavaScript the only error it returns is ReferenceError: readline is not defined, but readline is what the site says to use. What is wrong here?

Justin
  • 547
  • 3
  • 7
  • 15

6 Answers6

1

Try this:

function reverse(s){
    return s.split("").reverse().join("");
}

Caveats : https://stackoverflow.com/a/16776621/1636522.

Community
  • 1
  • 1
super
  • 2,288
  • 2
  • 21
  • 23
1
  1. The readline function doesn't take any arguments. Simply remove str and keep the line like this

    FirstReverse(readline());
    
  2. You are starting your loop with i = str.length, so when you do str[i] for the first time, you will get undefined. So, you should be starting from str.length - 1.

  3. Also you can return the backwards directly, you don't have to store it in str back, before returning.


function FirstReverse(str) {
    var backwards = "";
    for (var i = str.length - 1; i >= 0; i--) {
        backwards += str[i];
    }
    return backwards;
}

Also, I tested with these changes and it works.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

The first time the loop body is executed, i will have the value of str.length. That is one beyond the last element of the str, which is at index str.length - 1.

Fixed code:

function FirstReverse(str) { 
  var backwards = "";
  for (var i = str.length - 1; i >= 0; i--) {
     backwards += str[i];
  }
  str = backwards;  
  return str; 
}
Timothy Shields
  • 75,459
  • 18
  • 120
  • 173
  • i understand my error and this makes sense, but it still returns the same error, could it be a bug on the site itself? – Justin Apr 17 '14 at 03:13
0

It should be

function FirstReverse(str) { 
  var backwards = "";
  for(var i = str.length - 1; i>=0;i--){
     backwards += str[i];
      }
  str = backwards;  
  return str; 

}

because when indexing it begins from 0 to the length minus one of the string

Norly Canarias
  • 1,736
  • 1
  • 21
  • 19
0

Try

function FirstReverse(str) { 
  var backwards = "";
  for(var i = str.length - 1; i>=0; --i){
     backwards += str[i];
  }
  return backwards;  
}
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
0

You can apply this below code.

function FirstReverse(str) { 
  var backwards = "";
  for(var i = str.length - 1; i>=0; --i){
     backwards += str[i];
  }
  return backwards ;  


}
   
// keep this function call here 
console.log(FirstReverse(readline()));

It means when you write something on input, it will give you a reverse result.

Salim Murshed
  • 1,423
  • 1
  • 8
  • 19