2

Say I have an array of words:

let words = ['hello', 'world']

And I want to capitalize each one of them, what I'm doing is:

let words = ['hello', 'world']

for (let word of words) {
    word = word.toUpperCase();
}

But each word is not binded to the iterable element, and the end result is the unchanged array.

Is there any way to bind each of the words to the array elements?

(Besides of the classic for(i=0; i

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
Mauricio Machado
  • 613
  • 1
  • 5
  • 14
  • JavaScript strings are immutable, you cannot modify them. `word.toUpperCase()` returns an entirely new string. You need to replace the original string in the array with this new string. Better yet, replace the whole array. – le_m Jan 21 '18 at 16:57

1 Answers1

5

You can use map for this:

let words = ['hello', 'world'];

words = words.map(word => {
    return word.toUpperCase();
});
console.log(words);
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
Chris Riebschlager
  • 1,323
  • 1
  • 8
  • 12