0

Hi am trying to create a javascript function to reverse a word, but it seems the for loop is not begin executed and the holder variable is not being append in the for loop.

function jump(str){
    var holder ="";
    var len = str.length-1;
    for(var i =len; i == 0; i--){
        holder += str[i];
    }
    return holder;
}
console.log(jump("Just do it!"))
Arthur Decker
  • 1,191
  • 3
  • 15
  • 45

4 Answers4

4

Your loop is incorrect:

for(var i =len; i == 0; i--){
                  ^^^

The loop body only fires if that middle condition is "true". On its first iteration, i is something like 10, which means 10 == 0 is NOT true, aka false.

You probably want

for(var i =len; i >= 0; i--){

instead.

Marc B
  • 356,200
  • 43
  • 426
  • 500
3

I think this should work for you

var text = 'Just do it!';
var rev = text.split("").reverse().join("").split(" ").reverse().join(" ");
JTC
  • 3,344
  • 3
  • 28
  • 46
1
var result = str.split("").reverse().join("");
guitarman
  • 3,290
  • 1
  • 17
  • 27
1

The loop

for(var i =len; i == 0; i--){
    holder += str[i];
}

will only run when i is equal to zero - which won't be the case, since you set it up as the length of your (presumably) populated string. Try:

for(var i =len; i >= 0; i--){
    holder += str[i];
}
millerbr
  • 2,951
  • 1
  • 14
  • 25
  • As per the question, this is the best answer. And that one character really was the whole problem. – durbnpoisn Feb 03 '16 at 20:35
  • how do i reverse a sentence like Hello World to World Hello – Arthur Decker Feb 04 '16 at 03:28
  • Thats a bit more complicated and not in the scope of the original question. Off the top of my head, I'd say split the string into an array of words by splitting using spaces, then run your reversal code from above but on the array elements and not single characters – millerbr Feb 04 '16 at 08:05