Abhinav Alok Abhinav Alok - 3 years ago 151
Javascript Question

Cannot read property 'charAt' of undefined

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("Coding is not easy");

<!-- end snippet -->

Answer Source

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");

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download