-1

I have this doubt, this code is supposed to turn the first character in the word into caps

function ucFirst(str) {
    var newStr = str.charAt(0).toUpperCase();
    for (var i = 1; i < str.length; i++) {
        newStr += str.charAt(i);

    }

    return newStr
}
alert(ucFirst("john"));

this will print out "John" along with an undefined in the console.

Now I tried the exact same thing using the array values

function ucFirst(str) {
    var newStr = str.str[0].toUpperCase();
    for (var i = 1; i < str.length; i++) {
        newStr += str.str[i];
    }
    return newStr;
}
alert(ucFirst("john"));

I get this error in console "Cannot read property '0' of undefined"

Why is it so?

Arturs
  • 1,258
  • 5
  • 21
  • 28
Bazinga777
  • 5,140
  • 13
  • 53
  • 92

2 Answers2

1
str.str[0].toUpperCase();

should just be

str[0].toUpperCase();

If that isn't the case, you should try console.log(str) and find out what exactly str is but I believe this is your problem.

aug
  • 11,138
  • 9
  • 72
  • 93
  • When you declare a function in the console, it's always going to return an undefined. This is because you don't specifically return anything unless the function is called. A related question: http://stackoverflow.com/questions/11360904/console-returns-undefined – aug Sep 02 '13 at 18:16
  • yeah, it's working. Just wanted to know why the undefined shows up. – Bazinga777 Sep 02 '13 at 18:16
  • @Bazinga777 I updated my comment. There's a similar question related to it. – aug Sep 02 '13 at 18:18
1

It works. Replace all instances of str.str[ with str[

It reads out undefined because you're calling your string in object context and trying to refer to a property str, which is not a property, thus undefined. There is no String.str on the class object, nor is there a str.str on your string object (object used loosely) that you're passing.


Note: I want to add that while doing the replacement will fix your code, this is not the most optimal way to apply a propercase casting.

vol7ron
  • 40,809
  • 21
  • 119
  • 172
  • You have the right answer, but the wrong explanation. It doesn't resolve to `j` - it's trying to find the `str` property of `str`, which is undefined, and then the `0` property of that. – Dennis Sep 02 '13 at 18:29
  • @Dennis I think you're right. Looked at it too fast was thinking more like `str[str[0]]`. Note to self: only fools rush in – vol7ron Sep 02 '13 at 18:29