Can't understand how this javascript code control flow? [duplicate] - javascript

This question already has answers here:
How do JavaScript closures work?
(86 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 3 years ago.
This is the code of which i am not able to understand the flow of and also how the value of i persist even after the for loop ends.
var printNumTwo;
for (let i = 0; i < 5; i++) {
if (i === 2) {
console.log("now");
printNumTwo = function() {
console.log("inside");
return i;
};
console.log(i);
}
console.log(i);
}
console.log(printNumTwo());
The output of the program is
0
1
now
2
2
3
4
inside
2

reason of this behavior is Closures
A closure gives you access to an outer function’s scope from an inner
function. In JavaScript, closures are created every time a function is
created, at function creation time. mozilla doc
var printNumTwo;
for (let i = 0; i < 5; i++) {
if (i === 2) {
console.log("now");
printNumTwo = function() {
console.log("inside");
return i;
};
console.log(i);
}
console.log(i);
}
console.log('now calling printNumTwo()')
let s=printNumTwo();
console.log('now printing return value of printNumTwo()')
console.log('retrun value of PrintNumTwo is:'+s);

Related

Does the function call have access or retain the value of a local var variable of its parent function because I declare that variable as var? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Explanation of `let` and block scoping with for loops
(5 answers)
Closed 7 months ago.
I expect the calling of the first element in the array to print out the number 0. However, it prints 5. Does the function call have access to i of its parent function because I declare i as var? If I declare i as a let variable, it prints 0 as expected.
0-closureBug.js
function makeFunctionArray() {
const arr = []
for (var i = 0; i < 5; i++) {
arr.push(function() { console.log(i) })
}
console.log(i)
return arr
}
const functionArr = makeFunctionArray()
functionArr[0]()

Two similar for loop outputs different value [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 2 years ago.
I can't figure out the output of the following two loops. The only difference I notice is that the former use var and assigns a global scope and later create a local scope using const.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}
the output is 3 3 3 and 0 1 2.
According to my shallow knowledge, the first loop has to output 0 1 2.
If I print the value of i in the first loop.
for (var i = 0; i < 3; i++) {
console.log(i);
setTimeout(() => console.log(i), 1);
}
the output printed in the console by first console.log(i) is 0 1 2. While in the one wrapped within setTimeout vary.
Why?
var gets hoisted into the global scope, so when setTimeout is called it logs out whatever the value of i is when it is called, which would be 3 as the for loop has set i to 3 on its last iteration. Whereas let is scoped to the for loop and closes over the value of i on each iteration, thus printing 0 1 2.

I get strange output when i use var keyword in for loop with setTimeOut inside [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 2 years ago.
I have this code.
for (var i = 1; i <= 5; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
I don't understand the output from this lines of code:
The output in the console is number 6,and it says that is repeated five times.
If i use the let keyword for "i" then i get the output that i expect,
1,2,3,4,5 after one second
Why is that ?
var has scoping issues and that's why let was introduced.
In your for loop you are defining i, but actually it's stuck to the global scope, and after 1 second, the for loop would actually be done, and when the setTimeout callback is fired, i would have already reached 6 and it's read from the global scope.
In a nutshell, because i is stuck to the upper scope of for, each iteration modifies the calue of i and doesn't create another i.
If you change var to let, the issue is resolved.
setTimeout is async hence will execute after the loop is done, that s why you have i=6, put it in a self invoking function to retain the value of i or use let instead of var in your loop
for (var i = 1; i <= 5; i++) {
((i) => setTimeout(function() {
console.log(i);
}, 1000))(i)
}
for (let i = 1; i <= 5; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}

setTimeout within a for loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Calling functions with setTimeout()
(6 answers)
Closed 6 years ago.
I am trying to set a delay in the for loop in javascript. I want it to log i, have a delay, then log i, and so on. My question is, why does the following code work, having a function return a function as can be seen below:
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return function() {
console.log(i);
}
};
setTimeout(tick(i), 500 * i);
}
And the following code not work as expected:
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return console.log(i);
};
setTimeout(tick(i), 500 * i);
}
It prints out all the values in the for loop at once. Could someone please explain why this happens?
In both pieces of code, tick(i) is executed immediately in each loop
The difference is, that in the first example, tick(i) returns a function, which is called by setTimeout, and that outputs to the console
In the second example, the console.log is called immediately, undefined is returned, and setTimeout does nothing once the timeout has triggered as the given argument is not a function (or a string to be eval'd)

How does let in for loop work? [duplicate]

This question already has answers here:
Explanation of `let` and block scoping with for loops
(5 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 7 years ago.
var messages = ["Check!", "This!", "Out!"];
for (var i = 0; i < messages.length; i++) {
setTimeout(function () {
console.log(messages[i]);
}, i * 1500);
}
// -> prints 3* undefined
for (let i = 0; i < messages.length; i++) {
setTimeout(function () {
console.log(messages[i]);
}, i * 1500);
}
// -> prints out the array
I understand how "var" works and I'm quite used to it - the scope is functional. However the let statement is far from clear. I understand is has block scope, but why does THAT matter in the example? In that example the for loop is long time over with in both cases. Why does let print out the array?
let allows you to declare variables that are limited in scope to the
block, statement, or expression on which it is used. This is unlike
the var keyword, which defines a variable globally, or locally to an
entire function regardless of block scope.
Check out here more detailed info
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let

Categories