I’m new to programming and I’m working on LearnStreet’s “Writing functions”.
My question is with the following:
function capitalizeFirst(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
I get that if it were only :
return str.charAt(0).toUpperCase();
only the first letter would be returned and capitalized, but why does adding .slice(1) give the whole string back?
In the case of:
capitalizeFirst("i am apple");
// "I am apple" is returned
but with
function capitalizeFirst(str) {
return str.charAt(0).toUpperCase() + str.slice(0); // 0 instead of 1
}
capitalizeFirst("i am apple");
// "Ii am apple" is returned
Thanks ahead of time for any help/guidance towards this question.
Your confusion is natural. Almost every programmer makes an off by one error at some point in their life. So I’ll explain it to you using examples:
Consider the string
"Hello World!". In a computer it would be represented in memory as an array of characters. It would look like this:Now I want you to notice that there are only 12 boxes (characters), but 13 indices (
0to12). The indices are in between the characters.Note: The last index is always the length of the array.
A common mistake programmers make is that when they think of an array they think in terms of the boxes and not in terms of indices.
Important: An array is described in terms of its indices and not the number of boxes.
Now let’s look at the
slicemethod. This method takes two indices, the second one being optional. It returns a substring of the given string.For example if I only wanted
"World"from"Hello World!"I would extract it like this ("World"starts at index6and ends at index11):If I wanted everything after the space in
"Hello World!"(i.e. if I wanted"World!") then I could use a short form instead ofslice(6, 12). Here the12is implied, so I can simply useslice(6):I could even use negative indices to extract say the last character of the string without knowing the length of the string:
The
-1here represents the indexlength - 1. Sincelengthis defined as the last index it’s simply12 - 1in this case. Hence it returns everything after the index11.Understood? So now you understand the fencepost problem.
This is why you get the entire string as it is when you call
slice(0); and you everything after the first character when you callslice(1).Always remember to think in terms of indices and not boxes when dealing with arrays.
Read in between the characters.