-
When run through the console, the following code returns [“i”, “”, “m”] when inside of the for loop. When returned outside of the for loop, it returns [“p”, “o”, “t”]. Why is that?
-
In both instances, why does it only return the letters of one word in the array? Since it’s being run through a for loop that is supposed to stop iterating at the end of the array’s length, shouldn’t it return every single word’s letters to the console? Instead of returning [“i”, “”, “m”], for example, shouldn’t it return [“i”, “”, “m”, " ", “a”, " ", “l”, “i”, “t” … ] to the console?
function titleCase(str) {
var strSplit = str.toLowerCase().split(' ');
for(var i = 0; i < strSplit.length; i++) {
var letters = strSplit[i].split('');
return letters;
}
}
titleCase("I'm a little tea pot");
This is a part of the code to the “Title Case” algorithm challenge. If curious, the whole code is as follows. I’m just trying to understand how each part of the code works, because I had a lot of trouble with it. I’ve added comments to show my basic understanding of the code (please correct me if I’m wrong), but I’m still confused about the two points above.
function titleCase(str) {
var strSplit = str.toLowerCase().split(' ');
// splits into words
for(var i = 0; i < strSplit.length; i++) {
var letters = strSplit[i].split('');
/* splits each word into letters and becomes subarrays? ex: [["i", "", "m"], [" "], ["a"] ...] not sure if this is right */
letters[0] = letters[0].toUpperCase();
// takes first letter of each word in array aka subarray (?)
strSplit[i] = letters.join('');
// join split letters back together into words
}
return strSplit.join(' ');
// joins all words together to form a string
}
titleCase("I'm a little tea pot");