Reverse a word string.



  • I was trying to reverse my string and it almost worked, but I got a result of NaN or undefined. I tried to put the string in an array and then reversed the output of that array with a for loop running to zero.

    Can you give me a hint which direction i should have a look?

    One possible solution that was not working as intended was this:

    let newWord;
    const inputArray = Array.from(input);
    for (let j = inputArray.length; j >= 0; j--) {
      newWord += inputArray[j];
    }
    
    console.log(newWord);
    

    Thanks a lot.


  • administrators

    Welcome and sorry for answering so late.

    Maybe you already solved this issue. Just in case, here are some hints :

    1. You should always give an initial value to variables subsequently updated with the += operator.
    2. The index for iterating over an array or a string must vary from 0 to size of array - 1.

    Good luck!



  • Thanks Baptiste. I already solved it. Still a lot to learn. 🤓


Log in to reply
 

Looks like your connection to The JavaScript Way Community was lost, please wait while we try to reconnect.