Re:JavaScript Interview Question
by kenjackson on Thursday January 20, 2011 @01:37PM
(#2124705)
Does this work (from a non-JS person -- I like reading JS books, but don't code in it at all). This is certainly less elegant, but seems easier to follow:
[ Parent
| on HN ]
No, it doesn't because j is in the same scope as i.
Your confusion is because of a javascript quirk
for (...) {
var foo = bar
}
is actually the same as var foo
for (...) {
foo = bar
}
Notice how you only ever have one fooWhat you need is:
for (...) {
(function(bar) {
var foo = bar
})(bar)
}
which create a new foo every time you loopThat doesn't work. Variables in javascript are not block scoped but function scoped.
Re:JavaScript Interview Question
by kenjackson on Thursday January 20, 2011 @01:52PM
(#2124774)
Thanks. Good to know.