1

Can anyone please help me in understanding what am i doing wrong here. I am new to JavaScript programming.I am getting this error:

Cannot read property 'charAt' of undefined.

//Return the first letter of given string. 
function titleCase(str) {
  var newStr = str.split(' ');
  for (var i = 0; i <= newStr.length; i++) {
    console.log(newStr[i].charAt(0));
  }
}
titleCase("Hi there.");

<!-- end snippet -->
Abhinav Alok
  • 120
  • 1
  • 1
  • 16

4 Answers4

2

you looping condition needs to get updated. See you string include 4 words but iterating loop till i become 4 and starting from 0 i.e iteration will be done 5 times

function titleCase(str){
    var newStr = str.split(' ');
    for(var i = 0; i < newStr.length; i++){
        console.log(newStr[i].charAt(0));
    }
}
titleCase("Coding is not easy");
sumit chauhan
  • 1,270
  • 1
  • 13
  • 18
1

Just remove the = sign from this line

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

function titleCase(str){
    var newStr = str.split(' ');
    for(var i = 0; i < newStr.length; i++){
        console.log(newStr[i].charAt(0));
    }
}
titleCase("Coding is not easy");
Mohamed Abbas
  • 2,228
  • 1
  • 11
  • 19
1

function titleCase(str){
    var newStr = str.split(' ');
    for(var i = 0; i < newStr.length; i++){
        console.log(newStr[i].charAt(0));
    }
}
titleCase("Coding is not easy");

i <= newStr.length you were iterating till equal length, and starting from zero. There the problem is at end you are getting an undefined value. In your case the newStr array length is 5, and you are trying to get 5th element as well, while there is only 4 values present.

Escoute
  • 386
  • 4
  • 17
1

For developers coming with Angular Universal, domino, Server-Side Rendering (SSR) topics; it might be due to the reason you're using xhr2 package.

Therefore, removing it fixes the problem. Most probably you're using somehow like (global as any).XMLHttpRequest = require('xhr2');, then simply drop the line. More about this in #830 (comment)

Daniel Danielecki
  • 8,508
  • 6
  • 68
  • 94