0

I would like to understand why I can't use this construction to capitalize de first letter of my strings of the array with JavaScript.

function capitalize(array){
  for (let i = 0; i < array.length; i++){
    array[i][0] = array[i][0].toUpperCase() 
  }
  return lst;
}

I have already re-writed my code, to a way it works:

function capitalize(array){
  for (let i = 0; i < array.length; i++){
    array[i] = array[i][0].toUpperCase() + array[i].slice(1) 
  }
  return array;
}

But I wanted to understand more deeply why

2 Answers2

3

Strings are Immutable, so you can't modify a single letter of a string and have the original change, you have to assign an entirely new string.

let str = 'Hello';

str[0] = 'G' // doesn't actually do anything, since str is immutable

console.log(str)

str = 'G' + str.slice(1) // assigns a new string to str, so it works

console.log(str)
dave
  • 62,300
  • 5
  • 72
  • 93
0

Strings are immutable. You need to reassign the entire string.

let arr = ["this", "is", "a", "test", "string"]

function capitalize(array){
  for (let i = 0; i < array.length; i++){
    array[i] = array[i].replace(array[i][0], array[i][0].toUpperCase() )
  }
  console.log( array);
}
capitalize(arr)
J_K
  • 688
  • 5
  • 12