Title Case a Sentence Solution Questions

Isn’t this.substr(0, index) always this.substr(0, 0)? Why is it necessary? I attempted to use Javascript Tutor to see what’s happening in the user-defined replaceAt function, but I can’t see why this.substr(0,0) is needed because JT doesn’t show exactly what’s happening. The code is quickly run and spits out the result.

String.prototype.replaceAt = function(index, character) {
  return (
    this.substr(0, index) + character + this.substr(index + character.length)
  );
};

function titleCase(str) {
  var newTitle = str.split(" ");
  var updatedTitle = [];
  for (var st in newTitle) {
    updatedTitle[st] = newTitle[st]
      .toLowerCase()
      .replaceAt(0, newTitle[st].charAt(0).toUpperCase());
  }
  return updatedTitle.join(" ");
}

Hello there,

Why do you assume index is always equal to 0?

because of the arguments in replaceAt.

string.replaceAt(0, newTitle[st].charAt(0).toUpperCase());

The first argument index is 0.

In this case, yes. But, the function is made in such a way that you could choose to replace at a different index, and are not limited to always replacing the first.

If you don’t mind, would you be able to walk me through what happens to the first word in the sentence, “I’m” ?

I could, but here is an excellent resource for this:
http://pythontutor.com/javascript.html#mode=edit

Ah. Well, first thing to recognise is what is being passed to the replaceAt function:
In this case:

.replaceAt(0, newTitle[st].charAt(0).toUpperCase())
//Same as
.replaceAt(0, 'I')

Now, what does the substr method do: https://www.w3schools.com/jsref/jsref_substr.asp
In this case, the this keyword is referencing the object the replaceAt function was called on:
the lowerCase value of newTitle[st] == "I"

Now, substr(0,0) returns nothing. Same with substr(1) on an object of length 1.

So, replaceAt returns "I".

Hope that helps