Spot the JS error

Hallvord, our main BrowserJS guy has a little JavaScript gem in his entry “spot the JS error”:http://my.opera.com/hallvors/blog/show.dml/501962. The code is as follows:
==

// need to fake someMethod
Element.prototype.someMethod=function(){
// faking someMethod here
}
// we also have an insertBefore problem so let's fix that too
(function(oF){
// tweaking insertBefore here
})(Element.prototype.insertBefore);

==
Can _you_ spot the error without reading the comments on his entry?

5 Comments

  1. Asbjørn Ulsberg

     /  2006-11-14

    Shouldn’t there be a semicolon after the closing curly bracer of the first anonymous function (line 4)?

  2. Asbjørn,
    Why? Semicolons are optional in almost all cases in JavaScript.
    (Note, I do know the answer, just checking if you do 😉 )

  3. Asbjørn Ulsberg

     /  2006-11-15

    Because without the semicolon, there aren’t two statements as is intended, but just one, so the second statement becomes a parameter of the invocation of the first one. A bit complicated explanation, but that’s how I see it. 🙂

  4. Indeedy 🙂
    It makes more sense with the comments removed:
    bc.. Element.prototype.someMethod=function(){

    }
    (function(oF){

    })(Element.prototype.insertBefore);
    p. Which then can be seen to be this construct when the linebreak is removed:
    bc.. Element.prototype.someMethod=function(){

    }(function(oF){

    })(Element.prototype.insertBefore);
    p. More easily seen like this:
    bc.. Foo.returnedvalue = function () {

    }(bar)(baz);
    p. Because the ‘second’ command has parenthesis, it becomes a function call for the anonymous function in the ‘first’ command, passing the function inside it as a parameter. The returned value from that is then treated as a function, and executed by the final set of parenthesis, passing its own contents as a parameter. The final return value from that, is assigned to the initial variable (Element.prototype.someMethod in the original example).
    p. Try this example:
    bc.. returnedvalue = function (a) {
    return a ? confirm : alert;
    }(true)(‘PASS’);
    document.write(‘Return value from confirm was: ‘+returnedvalue);
    p. There is a lesson here, I suppose. Semicolons may be optional, but use them anyway, because very occasionally, what looks like two commands to you, is one command that runs completely differently to the JavaScript interpreter.

  5. Asbjørn Ulsberg

     /  2006-11-20

    bq. Semicolons may be optional, but use them anyway, because very occasionally, what looks like two commands to you, is one command that runs completely differently to the JavaScript interpreter.
    Indeed. I always program in the strictest mode available in the language I program in, to avoid problems like this. Too bad there isn’t a “strict” mode in JavaScript.