I am new to javascript and learning it from fcc and another site called grasshopper.
I am met with a lesson about recursive replace function which I can’t understand.
So it goes like this.
var wrongDocument = "This document ahs a typo in it. The other one ahs typo too.";
function changeSpelling(string, oldPart, newPart) {
if (string.includes(oldPart) === false) {
return string;
}
string = string.replace(oldPart, newPart);
return changeSpelling(string, oldPart, newPart);
};
console.log(wrongDocument);
console.log(changeSpelling(wrongDocument, 'ahs', 'has'));
I don’t understand why and how the return statement is calling the function that it is nestled in. What is happening here actually?
I also don’t understand the way we are writing the parameters and arguments.
Plus why this can’t be done with a if-else statement?
So I wrote my own code but I don’t know how correct it is.
var chat = "This document ahs a typo in it. The other one ahs too.";
var fix = (a, b) => {
if (chat.includes(a) === false) {
return chat;
}
else {
return chat.replace(a, b)
}
}
console.log(chat);
console.log(fix('ahs', 'has'));
Please explain the whole thing to me. Thank you.