Here are two code snippets, one using a traditional for loop and the other using a for...of loop.
export function reverseWordsWithTraditionalForLoop(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 reverseWordsWithForOfLoop(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(' ');
}
I'm curious about something - in the first snippet, my function
reverseWordsWithTraditionalForLoop
successfully reversed any word with a length greater than or equal to 5. However, in the second snippet, even though I modified the word
elements directly, the array singleWords
remained unchanged. Why is that?