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?

1
  • 2
    You are not using that upperCase value, you are simply uppercasing it, Thats it. Commented May 18, 2021 at 8:21

5 Answers 5

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);

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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)  

Comments

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);

Comments

1

let arr = ["new", "name", "need"];
    
arr = arr.map(item => {
   return item.toUpperCase();
});
    
console.log(arr);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.