Title Case a Sentence - My solution worked initially but I reset it to try again from scratch

Okay so I wrote the below code to pass this challenge.#
Now, it keeps retuning error

Cannot read property 0 of undefined

Despite that, when I do

console.log(strArr.join(’ ');

I actually do get the required output i,e, a string with each first letter capitalised

I am sure I initially passed this challenge using very similar code - maybe there is a small error made here.

Any pointers welcome as well as an explanation as to why the final console.log actually outputs what is needed to pass the challenge but for some reason returning strArr.join(’ ') does not work

Your code so far


function titleCase(str) {
  

let strArr = str.split(' ');



for (var row = 0 ; row<str.length ; row++) {

  strArr[row].toLowerCase();


strArr[row] = strArr[row][0].toUpperCase() + strArr[row].substr(1).toLowerCase();


console.log(strArr[row]);

console.log(strArr);

console.log(strArr.join(' '));


}

return (strArr.join(' '));





};

titleCase("shoRT aNd SHOut");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence/

The problem is with this line.

I am sure you meant to compare with strArr instead of str.

1 Like

Knew it, had to be something my eyes couldn’t see. Thanks!