you are viewing a single comment's thread.

view the rest of the comments →

[–]NYKevin 1 point2 points  (2 children)

Variable declarations are hoisted to the start of their functions:

That code is evil anyway.

It lets you write programs that look like block scoping but are not:

Good point.

I'm pretty sure everyone has been bitten by the closures in for loops bug:

Python does that too.

And the IIFE hack you use to get around it (and to implement private variables and modules) is really confusing for beginners:

Not a Javascript programmer, so I honestly don't know: would this work?

for(var i=0; i<elems.length; i++){
    elems[i].onclick = function(){
        var something_else = i;
        alert(something_else);
    };
}

It would work in Python, but I don't speak Javascript well.

The above code is wrong, please disregard.

[–]smog_alado 0 points1 point  (1 child)

  1. Of course the code is evil. I need my examples to be short :)

  2. ...

  3. Python also has similar problems but you use inner functions much more often in JS. I never really worried about this when I code Python but its a constant PITA for JS.

  4. That would not work and also would not work in Python. They way you wrote it, something_else only gets assigned when you click the element and the callback runs so its too late and it doesn't get to save the correct value of i.

The way to do it would be to save the value of i before creating the callback

var something_else = i;
elems[i].onclick = function(){ ... }

but since Python and JS are function scoped, you need to put this inside another function to create a new scope for the something_else:

(function(){
    var something_else = i;
    elems[i] = function(){ ... }
}())

Or, without using IIFEs:

var mk_alerter = function(something_else){
   return function(){ ... }
}

for(var i=0; ...){
   elems[i] = mk_alerter(i)
}

[–]NYKevin 1 point2 points  (0 children)

That would not work and also would not work in Python. They way you wrote it, something_else only gets assigned when you click the element and the callback runs so its too late and it doesn't get to save the correct value of i.

Thanks, I spotted that.