Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between for and for..of loops' output in a specific example

I have here two snippets of code, one using traditional for loop and the other using for…of loop.

export function spinWords(words: string): string {
  const singleWords: string[] = words.split(' ');
  for (let i = 0; i < singleWords.length; i++) {
    if (singleWords[i].length >= 5) {
    singleWords[i] = singleWords[i].split('').reverse().join('');
    }
  }
  return singleWords.join(' ');
}

export function spinWords(words: string): string {
   const singleWords: string[] = words.split(' ');
   for (let word of singleWords) {
     if (word.length >= 5)  {
       word = word.split('').reverse().join('');
     }
   }
   return singleWords.join(' ');
}

Why is that in the former snippet, my function spinWords was able to reverse any word with a length >5, whereas in the latter, the array singleWords remain unchanged even the word elements (with length>=5) were reversed?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

With the for loop you are manipulating the entry in the array, while with the for of loop you get a new variable word (which is correctly reversed) but only for the variable itself. You are not changing anything in the array. if you do:

export function spinWords(words: string): string {
   const singleWords: string[] = words.split(' ');
   for (let word of singleWords) {
     if (word.length >= 5)  {
       const idx = singleWords.indexOf(word);  
       singleWords[idx] = word.split('').reverse().join('');
     }
   }
   return singleWords.join(' ');
}

It will work the same as the for loop.

Playground

NOTE: while this works, its better to use a for loop (or using the built in forEach, that can access the index as well) for this use case here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading