0
let arr = ["new", "name", "need"]

for (let item of arr) {
  item.toUpperCase();
}

console.log(arr)            /// [ 'new', 'name', 'need' ]

I am trying to create an array of UpperCased items using for of loop. However I keep getting the same array. What am I doing wrong?

ChromeBrowser
  • 209
  • 2
  • 6

5 Answers5

1

This is because although you change the value of the array item to upper case, you never set the item back in the array.

This code will not change the original array item, but will rather create a new string that is uppercase:

item.toUpperCase();

Instead, loop through the array and set the array item to the upper case version like this:

let arr = ["new", "name", "need", "test"]

for (i = 0; i < arr.length; i++) {
  arr[i] = arr[i].toUpperCase();
}

console.log(arr)
Martin
  • 16,093
  • 1
  • 29
  • 48
1

toUpperCase returns a new string, it does not change the string in place.

let arr = ["new", "name", "need"]
const newArr = []
for (let item of arr) {
  newArr.push(item.toUpperCase());
}

console.log(newArr)

You can also do the same without an explicit loop using map

let arr = ["new", "name", "need"]
const newArr = arr.map(item => item.toUpperCase())
console.log(newArr);
Jamiec
  • 133,658
  • 13
  • 134
  • 193
1

You are not assinging that value anywhere. You have to assign it somewhere.

let arr = ["new", "name", "need"]
let updatedArr = [];

for (let item of arr) {
  const value = item.toUpperCase();
  updatedArr.push(value);
}

console.log(updatedArr) 

or simplyfied solution with map():

const arr = ["new", "name", "need"]
const updatedArr = arr.map(item=>item.toUpperCase());
console.log(updatedArr)  
Jax-p
  • 7,225
  • 4
  • 28
  • 58
1

toUpperCase returns an uppercased version of a string. It doesn't mutate the existing string.

You need to assign the return value somewhere.

let arr = ["new", "name", "need"]

for (let i = 0; i < arr.length; i++) {
  arr[i] = arr[i].toUpperCase();
}

console.log(arr);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

let arr = ["new", "name", "need"];
    
arr = arr.map(item => {
   return item.toUpperCase();
});
    
console.log(arr);
Ravi Ashara
  • 1,177
  • 7
  • 16