1

Here's my function:

function Ship(shipType) {

    this.name = shipType;
    this.detailedName = function() {
        var c=
            this.name.charAt(0).toUpperCase() +
            this.name.slice(1);
        return c;
    };
}

Now if I try to optimize = without intermediate variable, this doesn't work. Why?

function Ship(shipType) {

    this.name = shipType;
    this.detailedName = function() {
        return
            this.name.charAt(0).toUpperCase() +
            this.name.slice(1);
    };
}

Here's the fiddle that shows the problem: http://jsfiddle.net/VW5w3/

Olivier Pons
  • 15,363
  • 26
  • 117
  • 213
  • You're returning early from your function. Look up "semicolon insertion" and prepare to be chilled to the bone. – Kilian Foth Feb 25 '14 at 12:22

2 Answers2

1

Automatic Semicolon Insertion. The browser tries to correct your return to a return;.

If you put the return value into the same line as the return keyword, it will work correctly, have a look at this updated fiddle: http://jsfiddle.net/VW5w3/1/

return this.name.charAt(0).toUpperCase() + this.name.slice(1);

Community
  • 1
  • 1
Dennis
  • 14,210
  • 2
  • 34
  • 54
1

I believe it is because ; is not mandatory in JS, so return returns undefined. Write return in one line instead: return this.name.charAt(0).toUpperCase() + this.name.slice(1);

IProblemFactory
  • 9,551
  • 8
  • 50
  • 66