Let's dive deeper into your problem so that you can understand what is really going on here
function replaceAll(str, from, to) {
let result = ''
for(let i = 0 ; i < str.length ; i++)
if(str[i]===from) {
result = str.replace(from,to)
}
}
return result;
}
str
is a string type variable. String data-type is value type. When you change a character in a string it does not rewrite the content of the initial variable. It rather create a new string value and store it to memory.The previous value is garbage collected.
Initially str == loop
, now if you change first 'o'
with 'e'
then str
remains 'loop'. A new data is assigned to result
variable which holds the value 'leop'
. That is why in your for loop always same value is being assigned to result variable.
Let's visualize the process:
1st iteration :
result = 'loop'.replace('o','e') // leop
// result is now 'leop' and str remains 'loop'
2nd iteration :
result = 'loop'.replace('o','e') // leop
// as str remained 'loop', so result will again be 'leop
That's why result
variable remains the same after the for loop is completed.
Another thing to notice, although in 1st and 2nd iterations, value of result
variable is same ('leop'
), But in 2nd loop, initial 'leop'
from first loop is gurbage collected (thrown away)
in order to assign it another value (in our case another 'leop'
)