Sorry for the generic question. I have searched all over and found so many threads similar to this, however not one that answers my specific question - perhaps because the term I'm looking for doesn't even exist.
A friend of mine is learning programming, JavaScript specifically, and he asked me why this wasn't working:
var a = "Hello World";
a.replace("Hello", "Goodbye");
console.log(a) // Logs "Hello World"
The reason is because replace
does not modify a
, as strings are immutable in JavaSript. Becuase it returns a string, you'd need to do something like...
var a = "Hello World";
a = a.replace("Hello", "Goodbye");
console.log(a); // Logs "Goodbye World"
However, the alternative is a function like JavaScript's reverse()
, as it modifies whatever calls it. For example:
var fruits = ["Apples", "Oranges", "Bananas"];
fruits.reverse();
console.log(fruits) // ["Bananas", "Oranges", "Apples"]
When my friend asked me why his replace
wasn't working, I realized I was reaching for a word that I don't know (as far as I'm aware)...
"You have to set the string to "string dot replace", because the replace function is ________."
You don't need to set an array equal to "array dot reverse", because reverse is ________."
I'm familiar with prototype functions though I don't believe that's the word I'm looking for. Can anyone help me fill in these blanks?
You don't need to set an array equal to "array dot reverse", because reverse is a mutator function
. I think I've heard that terminology to refer to functions that "mutate" the instance which calls them. But you should probably double-check that somewhere else.