What kind of language is that ?

Consider the following code :

for (var i = 0; i < 20; i++) { var j = i; } alert(i + ' ' + j);

That’s javascript. It gives “20 19”. Would you expect that from a decent language ?

Update: Same result with a var j = 0; before the for loop. No surprise, actually.

Update 2: It seems what I’m complaining about has not been well received ;). I’m not complaining about the values, I’m complaining about the fact that there are values…

2006-03-11 19:20:42+0900

p.d.o, website

Both comments and pings are currently closed.

7 Responses to “What kind of language is that ?”

  1. Alex Says:

    C++ does the same thing.

  2. Matthew W. S. Bell Says:

    This is exactly what I would expect, barring variable scope problems.

  3. jd Says:

    Yes, I would expect that from any good language. (I don’t say that JS is good)

    Maybe you should unroll the loop in your head.. :)

  4. Philipp Kern Says:

    Eh, you need to surpass the condition actually. So the result makes perfectly sense to me. (At least that’s what I expect from for loops. I like constructs like each more, though.)

  5. yann Says:

    Existence of these variables outside the loop… berk!

  6. Olaf Conradi Says:

    JavaScript does not start a new scope for { } blocks. Only for function (object) declarations.


    Try this:

    for (var i = 0; i < 20; i++) { (function () { var j = i; })(); } alert(i + ‘ ‘ + j);

  7. Simon Says:

    I’m soundly in the school of coder, that needs a language that doesn’t do this sort of thing.

    Hey, if they hadn’t called it JAVAscript would you even try and compare it to a real language? But then shells have funny scoping for file handles, it is the idiosyncracies that stop normal (and/or intelligent people) from coding.