0

I don't understand why the for loop doesn't modify the chars of a string. this is

function testing (str) {
  let other_str = str
  for (let i = 0; i < other_str.length; i++) {
    other_str[i] = 'g'
  }
  return other_str;
}

console.log(testing('hey'));

I am aware that i can use other ways but i want to understand this.

rubotero
  • 753
  • 1
  • 8
  • 19

1 Answers1

2

Strings are immutable , convert the string to an array, do the modifications and join it back :

function testing(str) {
  let other_str = [...str];
  for (let i = 0; i < other_str.length; i++) {
    other_str[i] = 'g';
  }
  return other_str.join('');
}

console.log(testing('hey'));
Taki
  • 17,320
  • 4
  • 26
  • 47