Let variable declarations

I’ve been spending some time with Mozilla docs lately and noticed some lines that were like

let whatever = 123;

instead of the expected

var whatever = 123;

“let” being a common word it took a while to find info on it, but as best I could find it’s for “block level scope”.

Am I missing something? Is this something useful or just a way to avoid scope errors?

It’s only relevant where JavaScript 1.7 is supported.

Yes, let is to define a block-scope variable. You can read more about it at https://developer.mozilla.org/en/JavaScript/Reference/Statements/let

Any code though that might be run on Internet Explorer must remain compatible with JScript, which is Microsoft’s own variation of JavaScript 1.3 instead.

Thanks for the link to the docs Paul, searching for “let” wasn’t getting me anywhere. (“1.7” would have been better if I had only known).

I can see where it would come in handy. Right now if a function has a lot of for loops I make sure the “index” variables are all named different. Using let would make things easier and less error prone.

I find that using MDN as the keyword (for Mozilla Developer Network) helps Google get to the right place. That way a successful result can be obtained by searching for:
mdn let

I can see where it would come in handy. Right now if a function has a lot of for loops I make sure the “index” variables are all named different. Using let would make things easier and less error prone.[/QUOTE]

What helps is to place declared variables right at the start.

For example, with 3 loops:


var i;

for (i = 0; i < foo.length; i += 1) {
    ...
}
for (i = 0; i < bar.length; i += 1) {
    ...
}
for (i = 0; i < baz.length; i += 1) {
    ...
}

Notice how the initial expression for each for loop doesn’t use var declarations? This helps to make them more portable and consistent.

Or when they are nested:


var x, y, z;

for (x = 0; x < foo.length; x += 1) {
    for (y = x; y < bar.length; y += 2) {
        for (z = y; z < baz.length; z += 1) {
            ...
        }
        ...
    }
    ...
}

Mind you, with that last, lot I’d be tempted to break them up in to separate functions, and use the forEach method on them instead.