Title case a sentence ::: stuck

could somebody please explain why my for loop is only getting to first word in sentence???
the output im getting is “Iim” while i was expecting to get [“Iim”," Vvery", “Sstuck”, “Oon”, “Tthis”, “Pproblem” ]

function titleCase(str) {

var array = str.toLowerCase().split(" ");
var help;

for (i =0; i < array.length; i++) {	

help =  array[i].charAt(0).toUpperCase() + array[i];

return help;
}
}

titleCase(“Im very stuck on this problem”);

You have return in your for loop. Move it outside.

The explanation is that the ‘return’ statement breaks the execution of the current code and goes back (“returns”) to the calling program passing your “help” variable back to the calling program.

So with the ‘return’ statement inside the for-loop, the loop will run once and on it’s first iteration, it will return, aka break out of the loop, and send the result of what was output from that 1 pass of the loop, in this case, the “lim” element.

You want the loop to finish, and after it finishes, then return the result back, so put your return statement after the close of the loop (the “}” curly brace).

1 Like