Title Case My Code

Title Case My Code
0

#1

Tell us what’s happening:
here is my code its working properly but in output it gives undefined plus the main output

Your code so far

function titleCase(str) {
  var sum;
  var arr=str.toLowerCase().split(' ');
  for(var i=0;i<arr.length;i++)
    {for(var j=0;j<arr[i].length;j++)
      {
       if(j==0)    
         { 
       sum+=arr[i][0].toUpperCase();  
        if(j==arr[i].length-1)
        sum=sum+' '; 
         }
           else{
        sum+=arr[i][j];
        if(j==arr[i].length-1)
        sum=sum+' '; 
         
       }
      }
    }
  
 
    
  return sum;
}

titleCase("I'm a little tea pot and what a game");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36.

Link to the challenge:


#2

You solution was not correct, because it was putting ‘undefined’ at the beginning of the string. The reason it was doing that is because you declared a variable called sum but did not assign it a value, so JavaScript automatically assigned it undefined. Then in the first iteration of the nested for loop, you did:

sum+=arr[i][0].toUpperCase();  

Since sum was originally undefined and you concatenate arr[i][0]. toUpperCase() (which is a string) to it, sum treats undefined as a string and joins them together.

To fix this issue, you should initialize sum to a blank string.


#3

Any way to correct it
i have tried sum=’’;but id doesn’t work but undefined is removed


#4

Setting sum=’’ definitely better. The only thing that is preventing you from solving the challenge is the extra space you tag onto the end of the string.

The line:

sum=sum+' '; 

allows you to add the space between the words, but you do not want a space on the end of the last word. You can either fix this with an if statement or learn about the trim() function.