This question already has answers here:
What is the difference between "let" and "var"?
(39 answers)
Closed 5 years ago.
Why the following code returns 10 times 10 and print hey as first line?
for (var i = 0; i < 10; ++i) {
setTimeout(() => console.log(i), 0)
}
console.log('hey')
When if instead I use let I get properly the counting, but why the line hey is always printed first?
for (let i = 0; i < 10; ++i) {
setTimeout(() => console.log(i), 0)
}
console.log('hey')
My question actually contains two:
First why hey is printed first.
Why using let the counting is printed properly.
setTimeout() is an asynchronous function
console.log('hey')
won't wait for it to finish before printing, since JS is single threaded, it would wait for the program to run and then pick the setTimeout() from event queue
difference between let and var can be found in this answer. Basically since let has scope limited to the for loop, the setTimeout can refer to only 1 value of i. If we use var then it is function scope and each function would get the same value of i
Related
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 months ago.
If I run this code then it console 4 at 5 time, can anyone explain why it is happening ?
let number = 1;
for (var i=0; i<5; i++){
number=i;
setTimeout(()=>{
console.log(number)
},1000)
}
Also if I modify this to as below then output is 5 times 5 ?
for (var i=0; i<5; i++){
setTimeout(()=>{
console.log(i)
},1000)
}
And why it prints 0 to 4 when we use let like
for (let i=0; i<5; i++){
setTimeout(()=>{
console.log(i)
},1000)
}
Its a typical use case of var being functional scope ,every iteration of for loop shares the same value of var (doesn't creates a new scope as var being functional scope) which is kind of global in here
so when the last condition arrives i<5 i is already has become 4 ,and it is shared by every callback of setTimeout so they all prints 4 ,4 times
But in case of let a new scope is formed in every iteration ,as let being a block scope (for loop has a block scope)
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 4 years ago.
Below is the simple jest test block in JavaScript, under the describe I've written a simple test to print the current index of the loop (until 5) of which it is put in. But the result is always Test 5
describe("Hello", async ()=>{
for(var i=0; i<5; ++i){
test(``Test ${i}``, async ()=>{
await console.debug("Test "+ i);
});
}
});
Can someone please clarify, how does it work?
Use let instead of var, let will preserve the scope for each async call. So in each loop, new values of i will be passed to your method and those values will stay preserved. In the case of var the variable i will be function scoped (that function being the one you use as callback in describe()) so when your asyn method resolves, you will see the value of i which exists inside your callback, since the loop would already have ended the value would be 5.
for(let i=0; i<5; ++i){
// dummy async method
setTimeout(() => {
console.log(i)
}, 2000)
}
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
let keyword in the for loop
(3 answers)
Closed 4 years ago.
Why output is 10 when use var and with let it works the loop.
Edit the output is 11 but why let and var are different
var funcions = [];
for (var x = 0; x <= 10; x++) {
funcions.push(function() {
console.log(x);
});
}
funcions.forEach(
function(func) {
func();
}
);
I know that let, is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block it’s defined in, which is not always the entire containing function.
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 5 years ago.
Consider these 2 snippets:
With let:
for(let i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 100)
}
With var:
for(var i = 0; i < 10; i++) { //HERE
setTimeout(function() {
console.log(i);
}, 100)
}
From my understanding, let only affects the scoping of the variables, so why are the outputs of the 2 loops should be same, so why does let print 0-9 and var prints 10 10 times?
Because you have a timeout in your loop, none of your logs are being called until the entire loop is finished.
After the loop is finished, the value of i is 10 if you use var.
But let is block scoped, meaning it's the same value anywhere in the loop, even in an async function like setTimeout (unless you manually change it inside the loop) - because the loop creates a new scope on each iteration, it's almost like each iteration creates a new "instance" of the i variable when you use let, whereas using var each loop is using the same instance of the i variable.
This question already has answers here:
setTimeout in for-loop does not print consecutive values [duplicate]
(10 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
I'm new to asynchronous programming, and I'm having a hard time getting the concept.
Please help!!!
Ive come up with a simple example:
for (var i = 1; i <= 10; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
All I want is to print the indexes in ascending order but due to asynchronous action forced by the setTimeout i'm getting the last index printed out 10 times.
I understand why this happens...
No matter what I've tried (I don't think my misunderstanding needs elaboration) I failed solving this stupid riddle...
Im obviously missing something basic.
Please help me figure it out.
It's because all those functions use the same variable i, which is equal to 10 during invocation of them. Try something like this:
for (var i = 1; i <= 10; i++) {
setTimeout((function (k) {
return function(){
console.log(k);
}
}(i)), 1000);
}
It's because JavaScript has closures. You can read about them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures