** Explanation Needed ** Title Case a Sentence

Link to challenge:


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

What does st represent? Where did it come from?

Also, what does replaceAt do? There’s information online about replace(), but none about replaceAt.

This solution (which is one of many ways to solve the problem) uses a for…in loop.

The person who wrote the code you’re looking has to have written a function replaceAt, it’s not a built-in method, that’s why you can’t find any documentation.

…that they attached to the String prototype so that they could do "some string".replaceAt(0, ...etc)

Edit: here’s an example:

String.prototype.replaceAt = function (index, replacement) {
  const chars = this.split("");
  chars[index] = replacement;
  return chars.join("");

console.log("hello".replaceAt(0, "H"))
// "Hello"

Note: this is just for example purposes, don’t do this in practice. Monkey-patching JavaScript builtins is not really advisable. For one thing, it’s extremely confusing when you end up with code that looks like it’s just using built in functions when in fact it’s custom stuff, as you have discovered.


I’m still confused as to what st in the for…in loop represents.

Do you have a solution you wrote that we can compare with this solution? That would help us explain.

The basic idea is that the sentence is being broken up into words and then they loop over each word and change it to match the instructions.

1 Like

Is the word st something we come up with ourselves (like a function parameter) or does it have a specific built-in function?

Did you look at the documentation on the for…in loop? It’s just a variable name like the other examples on the MDN link. I don’t particularly like the cryptic variable name the author choose though.

1 Like

It’s just a variable, it can be called anything. In a loop, you normally have a variable which you use to track the current item, and that variable needs a name. The variable has some value assigned to it so you can access the value in the loop body. Then the loop runs and the variable is assigned the next value so you can access it and so on.

Here it’s called “KEY”

for (var KEY in someObject) {

Here it’s called “INDEX”:

for (var INDEX = 0; INDEX < someArray.length; INDEX++) {
  console.log(some array[INDEX]);

Here it’s called “ITEM”:

for (var ITEM of someIterable) {

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.