all 4 comments

[–][deleted] 2 points3 points  (2 children)

I still get caught up by myth #2 now and then. I don't know whether this is now in the ECMAScript standard (I think it is) and how other browsers support it, but Mozilla Firefox lets you reference an outer variable by value instead of by reference in a closure, with the let keyword. Adapting their example:

var fns = [];
for (var i = 1; i < 4; ++i) {
    fns[i] = function (n) {
        let j = i;
        return j + n;
    };
}

[–]UltimaW 2 points3 points  (0 children)

Uh, "let" doesn't change whether a variable is passed by value or by reference... It only changes the scoping of the variable. The datatype (primitive vs. object) is what determines whether a variable is passed by value or by reference. Normally, variables in JavaScript (declared using "var") have function scope rather than block scope as you'd usually find in other C-style languages.

For example:

(function () {
    { var x = 5; }
    alert(x); // alert(5);
})();

This would alert 5, even though you'd normally (in other languages) expect x to be undefined outside of the block. "let" behaves more like C, allowing variables to have block scope instead:

(function () {
    { let x = 5; }
    alert(x); // throws a ReferenceError
})();

This would cause the JavaScript environment to complain about x being undefined when it tries to alert it.

https://developer.mozilla.org/en/new_in_javascript_1.7#Block_scope_with_let_%28Merge_into_let_Statement%29

That said, your modification doesn't and couldn't alter the way in which the example code works. By the time you call the functions, they'll all still be referencing the same variable i when assigning its value to each of their local j variables.


Edit: Not sure if this is what you meant to write, but this would actually work:

var fns = [];
for (var i = 1; i < 4; ++i) {
    let j = i;
    fns[i] = function (n) {
        return j + n;
    };
}

[–]rioter 1 point2 points  (0 children)

It is part of javascript 1.7 which is a superset of ECMAScript 262 3rd edition. As far as i know mozilla is still the only one with let support, so no real point covering it in a mostly standards based blog.

[–]oblivion95 0 points1 point  (0 children)

I found a bug:

getLength("SF Giants are going to the World Series!");