389747 (5) [Avatar] Offline
#1
Hello,

P. 35/36 show this example:

let symbols = ['FB', 'GOOGL', 'CTXS'];
for(let symbol of symbols) {
ajax(`<host>/stocks?symbol=${symbol}`,
response => {
console.log(`Symbol: ${symbol} | Stock price: ${resp.price}`);
});
}

and imply that it outputs:
"Symbol: CTXS | Stock price: 119.379997"
"Symbol: CTXS | Stock price: 747.599976"
"Symbol: CTXS | Stock price: 85.500000"

I suspect that this is wrong. There's a reason why Javascript adopted let and const in place of var.
Keyword 'let' is supposed to introduce a new scope per iteration. In Chrome for instance, this code:

let symbols = ['FB', 'GOOGL', 'CTXS'];
let i = 1;
for (let symbol of symbols) {
setTimeout(() => console.log(`<host>/stocks?symbol=${symbol}`), i * 500);
i = i + 1;
}

outputs FB, GOOGL and CTXS, so correct values are captured.

Actually, this whole example misses the point: it's not the capture that's problematic, it's the number of concurrent ajax calls. So why not state it clearly.

Thanks,
MK
331872 (130) [Avatar] Offline
#2
Absolutely. This used to be a problem with "var" not "let". We'll be addressing this.

Thank you!