What is st in the javascript code?

this code gets a string and chang the first letters into uppercase state:

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(" ");
}

basically I don’t understand this part:

 for (var st in newTitle) {
    updatedTitle[st] = newTitle[st]
      .toLowerCase()
      .replaceAt(0, newTitle[st].charAt(0).toUpperCase());
  }

I also don’t understand this :confused:

val.replace(val.charAt(0), val.charAt(0).toUpperCase());

st is the index of each of the split string array items.

for…in loops are a little unintuitive, whereas for…of loops are a bit easier to reason about. A for…of loop would hold the individual word from the split str array.

Btw, st is an unhelpful variable name, which adds to the confusion!

1 Like

This code is bad to put it lightly. Particularly:

  1. Modifying String prototype as well as any global constructor, is considered to be a bad practice and should be avoided if possible. In this particular example it is very easy to avoid.
  2. First of all, this line will not split string into array of characters.

…and secondly, any string is already camouflaged array of characters and one should prefer iteration method to do that:

const str = 'string';
const arr = [...str]; // It's not the same as .split()!
  1. For in loop should never be used on arrays and to be honest considering amount of available methods you most like will never have to use for of loop either.

And bonus: .join(" ") will not work in the way you expect as well.

1 Like

Thank you so much for the explanations @snigo @JacksonBates I appreciate it