Search code examples
javascriptfor-loopcountdownflipsnakecasing

How to count backwards


Hey guys im developing something and I need to fix this please give me some feedback on how to improve this. (how to make it cleaner, easier to read , etc). Here's the code!

function wordFliper(word) {
    let wordOutput = "";
    let reverseIndex = word.length - 1;
    for (let index = reverseIndex; index >= 0; index--) {
      let storage = word[index];
      wordOutput = wordOutput + storage;
    }
    return wordOutput;
  }

Solution

  • I would remove some variables (variables that are used once in loop and then assigned to a function variable) to reduce code and rename one like this:

    /// <summary>Function to flip words backwards</summary>
    /// <param name="word" type="string">Word to be flipped</param>
    /// <returns type="string">Word flipped</returns>
    
    function wordFlipper(word) {
        let flippedWord = "";
        for (let i = word.length - 1; i >= 0; i--) {
          flippedWord += word[i];
        }
        return flippedWord;
    }
    

    Also IMHO use i variable instead of index (for loop incrementer)

    And Also get used to commenting your code, to know what is for the functions you're writing

    I hope you helped to keep your code clean for further programming and happy coding!