Reputation: 853
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.
Upvotes: 0
Views: 44
Reputation: 17654
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'));
Upvotes: 2