Calling an arrow function in .replace()

Hi.
For the Chapter: Basic Algorithm Scripting: Title Case a Sentence, where you’re supposed to write o function that capitalizes every first letter of each word.
One of provided solutions looks like this:

function titleCase(str) {
  return str.toLowerCase().replace(/(^|\s)\S/g, (L) => L.toUpperCase());
}

My question is how the (L) => L.toUpperCase() works, i don’t pass to it any arguments, so how does it know what values it is supposed to take in? Could you out some article about that?

The first parameter passed to the .replace callback is the string matched by the entire regex. Capture groups are passed as extra parameters after that, one for each group. The portion of the string that was matched by the whole regex is then replaced by the return value of the callback.

As for how L => L.toUpperCase() works, it’s because .toUpperCase is a method on strings, so it’s more or less equivalent in this case to a function like toUpperCase(L). It doesn’t work exactly like that, but it suffices to say that a method always “acts on” the thing to the left of the dot. When methods are covered in the OOP section of the curriculum, that behavior gets explained further, in terms of the keyword called this.

1 Like