Achtung, minen!

One more “cool” thing about JS:

somevar = 100;
      function test()
        somevar = 1;
        return somevar;
        if(false) { var somevar; }

Try to guess first what these two alert()s will output in JS.

You did?

Then try to see this code running alive: js-mine.

That is what Web2 is supposed to be based on… Huh?

[update] Here is a link on Doug’s Crockford talk at Google about JS.

Doug Crockford is behind JSON spec and ECMAScript 3.1.

Probably Doug’s speech may explain why I decided to go with TIScript rather than implementing JS as it is.

6 thoughts on “Achtung, minen!”

  1. Yeah, especially that source code from post is defferent with the actual source code. It will hurt your readers brain, I think 🙂

  2. There is nothing interesting about this article. I guessed what result would be returned and was correct. Not only is this how JS functions but how almost any language will function. Further, the if (false) statement is (obviously) superfluous since it can never be true, adding absolutely no value to your example either.

  3. On his website and in his books Doug explains quite logically why this happens. If I still get it right any var in a function defines a local variable. The if is NOT a different scope. His advice therefor was to initialize any variables used at the beginning of a function. So as the local var inside test() is a local var it is 1, and never changes the global var somevar. You probably knew that yourself… But I think if one follows especially any advice in javascript – the good parts javascript indeed is a very nice language. and regarding its history it is amazing what it is capable of…

  4. To Christof:

    I know two languages that have no block scope for local variables: JS and Python (they are actually surprisingly close to each other in many other areas).

    For the Python with its peculiar syntax that is probably not that bad.
    But for the JS that is using C/C++/C#/Java/etc. type of syntax such thing is a huge surprise. At least for me.
    When designing TIScript I hadn’t even an idea that variable visibility/scope can be implemented other way in such syntax.

    That dead code `if(false) { var somevar; }` in my example below will never execute and is a good chance to be removed by bytecode optimizer but its existence (smell of var) creates very bad side effect. It is just enough to write `var YourCoolNamespace = …` somewhere in depths of your function in Galaxy far,far away and you will spend rest of your life finding who hijacks YourCoolNamespace.

    And yet this function:

    function foo 
      var a = 1; 
      {  var b = 2; }
      {  var c = 3; }

    in TIscript will have storage for two values in runtime and in JS by definition it will have 3 slots for all variables. If to think about recursive calls and things like closures… size matters indeed.

Comments are closed.