Wednesday, May 14, 2008

JavaScript: The Return [no LineTerminator here] Statement

I was just reading JavaScript: The Good Parts by Douglas Crockford, and came across this statement:

I always use the K&R style, putting the { at the end of a line instead of the front, because it avoids a horrible design blunder in JavaScript's return statement.

A while back, I was introduced to using closure to help get rid of unnecessary global variables in JavaScript by a friend at work, along with the book Pro JavaScript Design Patterns. Instead of something like this:

var myString = 'hi';

function doStuff() {
    alert(myString);
}

You write something like this:

var myNamespace = function() {
    var myString = 'hi';

    return {
        doStuff: function() {
            alert(myString);
        }
    }
}();

But, because I like BSD style, I did this, with line breaks before the opening braces:

var myNamespace = function() 
{
    var myString = 'hi';

    return 
    {
        doStuff: function() 
        {
            alert(myString);
        }
    }
}();

When I tried to call doStuff, I promptly got the JavaScript error "myNamespace is null or not an object."

After much head-scratching and debugging, I learned the hard way that ECMAScript defines the return statement like this:

return [no LineTerminator here] Expressionopt ;

Let me put that a slightly different way:

return [!!!NO LINE_TERMINATOR HERE!!!] Expressionopt ;

And that's the story of how I became a convert to using K&R style when coding JavaScript.

No comments:

Post a comment