Consider the following (your code, but I added a console.log before the if
block
const testSentence = 'This is a really really really very very good sentence';
const betterWords = testSentence.split(' ');
const improveWords = betterWords.map(word => {
let reallyCount = 0;
let veryCount = 0;
console.log(`reallyCount: ${reallyCount}, veryCount: ${veryCount}`);
if (word === 'really' && reallyCount % 2 !== 0) {
reallyCount = reallyCount + 1
return word;
} else if (word === 'really' && reallyCount % 2 === 0) {
reallyCount = reallyCount + 1;
return 'truly'
} else if (word === 'very' && veryCount % 2 === 0) {
veryCount = veryCount + 1;
return 'vastly';
} else if (word === 'very' && veryCount % 2 !== 0) {
veryCount = veryCount + 1;
return word;
} else {
return word;
}
});
console.log(improveWords.join(' '));
The output of that is
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
This is a truly truly truly vastly vastly good sentence
However, if you moved your
let reallyCount = 0;
let veryCount = 0;
to before calling the map function so they aren’t declared inside the arrow function, then the output would be:
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
reallyCount: 0, veryCount: 0
reallyCount: 1, veryCount: 0
reallyCount: 2, veryCount: 0
reallyCount: 3, veryCount: 0
reallyCount: 3, veryCount: 1
reallyCount: 3, veryCount: 2
reallyCount: 3, veryCount: 2
This is a truly really truly vastly very good sentence