Home > Back-end >  Javascript To create a reverse sentence , what have I done wrong?
Javascript To create a reverse sentence , what have I done wrong?

Time:02-05

to achieve

reverse("cool"); // "looc"


reverse("The quick brown fox jumps over the lazy dog") //"god yzal eht revo spmuj xof nworb kciuq ehT"

reverse("anna") // "anna"

My code is

function reverse(sentence) {
  let reversedword = ""
  for (let i = sentence.length; i < 0; i = i-1) {
    reversedword = reversedword   sentence[i];
  }
  return reversedword;
}

console.log(
  reverse("cool")
)

console.log(
  reverse("The quick brown fox jumps over the lazy dog")
)

console.log(
  reverse("anna")
)

The output of my code is empty "". Can someone help to fix my code so that I can understand?

CodePudding user response:

You should start the loop with length-1, and have the condition to i>=0.

Explanation:

You want to initialize your counter with the last character of your string. For example hello has 5 characters.

And then the last character's index is 4 (Strings as arrays, are "zero-indexed"). So the first character (h) index is 0 and the last is 4.

That's why you would initialize your array with sentence.length-1.

Then, you want your loop to continue while your index (i) is positive, or equals 0 which means that you reached the first character of your string.

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for#syntax

function reverse(sentence) {
  let reversedword = ""
  for (let i = sentence.length - 1; i >= 0; i = i - 1) {
    reversedword = reversedword   sentence[i];
  }
  return reversedword;
}

console.log(reverse("cool"));

CodePudding user response:

there are two things which needs to be corrected

The condition in for loop is wrong which says i<0, it should be i > 0, since we will stop when i becomes zero as this is reverse loop.

Second thing is accessing the index, sentence[i], i will be out of bound index as javascript array starts from index 0.

Please find below as the corrected and working code

function reverse(sentence) {
  let reversedword = ""
  for (let i = sentence.length; i > 0; i = i - 1) {
    reversedword = reversedword   sentence[i - 1];
  }
  return reversedword;
}

console.log(
  reverse("cool")
)

console.log(
  reverse("The quick brown fox jumps over the lazy dog")
)

console.log(
  reverse("anna")
)

CodePudding user response:

Just fix the for loop you'll get the desired out

function reverse(sentence){
    let reversedword = ""
        for ( let i = sentence.length - 1 ; i >= 0 ; i = i-1 ){
            reversedword =  reversedword   sentence[i];
        }
    return reversedword;
    }

console.log(reverse("cool")); // "looc"


console.log(reverse("The quick brown fox jumps over the lazy dog")) //"god yzal eht revo spmuj xof nworb kciuq ehT"

console.log(reverse("anna"));
  • Related