`var` and `let` behaviour in arrow functions [duplicate] - javascript

This question already has answers here:
What is the difference between "let" and "var"?
(39 answers)
Closed 5 years ago.
Why i behaves differently in arrow functions? Is it because var x is being reassigned while let x is being created new for each iteration?
//prints 55555
for(var x = 0; x < 5;x++){
setTimeout(()=>console.log(x),0);
}
//prints 01234
for(let x = 0;x < 5;x++){
setTimeout(()=>console.log(x),0);
}

It has nothing to do with arrow functions. let is block level scope, so each time you enter the body of the loop, you get a new variable.
In your case, the timer function prints differently, because of the closure being created around x.
var provides one variable that all iterations of the loop (and therefore, all timer callbacks) share, hence you get the last value of the variable shared by each timer callback. Remember, the timer callbacks won’t run until your loop is finished and, at that time, x has been incremented to 5.
let gives each timer callback it’s own value because of the block scope. So, even though the timer callbacks don’t run until the loop is finished, each callback has a closure around a differently scoped variable.

let in the loop can re-binds it to each iteration of the loop, making
sure to re-assign it the value from the end of the previous loop
iteration, so it can be used to avoid issue with closures.
Read more here: http://www.jstips.co/en/javascript/keyword-var-vs-let/

Related

'const' scope in for loop JavaScript [duplicate]

This question already has answers here:
Explanation of `let` and block scoping with for loops
(5 answers)
Re-assign/declare a const variable in a JavaScript for-loop and save it more than one time with different values?
(2 answers)
const variable can be redeclared inside while loop even though it should be constant
(1 answer)
Closed last year.
In the code below, is ele available only for an individual iteration of the loop?
for (var i=0; i<3; i++){
const ele = i
console.log(ele)
}
I'm thinking this should be the case, otherwise there will be a
Syntax Error: Identifier 'ele' has already been declared
every time the loop iterates after the very first time.
I could not find a way to confirm this using console.log(), so looking for a concrete answer.
EDIT: To clarify, I understand that ele is valid within the for loop only. My question is specifically if the scope is ' reinstantiated' every iteration of this loop or not. It definitely looks like it, but I haven't heard or read that explicitly anywhere yet.
why do not directly use console.log(i) ?
howei think you should try to use var or let instead of const

Why do var and let produce different outputs in closures? [duplicate]

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.

what's the statement execution order of this JS closure ? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
I have known the key of closure is about scope. But I don't know the specific execution order of it.
A classical code from 《Professional JavaScript for Web Developers 3rd Edition》about closures.
function createFunctions(){
var result=new Array();
alert('haha');
for(var i=0;i<10;i++){
result[i]=function(){
alert(i);
return i;
};
}
return result;
}
var a=createFunctions();
To my surprise, 'haha' was alerted while none of 'i' were alerted.I was just assigning the function to variable a.Why the statement "alert('haha')" was alerted while the cycle wasn' t executed?
when I add the below code,
var a=createFunctions();
alert(a[2]);
why it alerted like this
function (){
return i;
}
not like
function (){
return 2;
}
Furthermore when I add the below code, what will being the order of statements executed especially the statements in the cycle.
var a=createFunctions();
alert(a[2]());
When you call
var a=createFunctions()
alert('haha') is executed immediately, and an array of 10 functions is created and assigned to the variable 'a', each function alerting 'i' and returning it.
However, by the time any of those functions is called (provided you call them after creating them) the value of i is '10' (the loop termination value). So every time you call one of the functions, with
alert(a[x]())
( with any value of x = 0 thru 9 )
it will alert(10) as the function executes and alert(10) again when it returns.
Why the statement "alert('haha')" was alerted
Because it was an alert statement in the function you called.
while the cycle wasn' t executed
The cycle was executed. The cycle just creates some functions and assigns them to positions in an array. You never call any of those functions.
and when I add the below code, what will being the order of statements executed
It depends where you add it.

Scope in Javascript: Why is the answer 10, not 20? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 6 years ago.
I'm learning about scope in JS. I was just thinking that I'm getting the hang of it, when I came across this example:
var x = 20;
for (x = 0; x < 10; x++) {
}
// returns 10
console.log(x);
Why 10? I would have expected 20 as an answer.
When you start your for loop, you are currently writing for (x = 0). This is overwriting the var x = 20 statement, so now x = 0. The loop continues to run as you would expect.
When you use the var keyword, you are creating a new variable in that current scope. Because you are not initializing your for loop with the var keyword, basically, JavaScript looks for an existing variable called x. It finds the one you created with var x = 20 and will overwrite the reference, so now x = 0.
It returned 10 because for loop changed it by incrementing. You didn't create new variable, so Javascript automatically overwrote already existing. This is because you created for loop, which has that variable as an initial expression. It happens when you want refer to a variable, that doesn't exist in lexical environment, syntax parser take it from outside. It means in this case, that from global object where you declared variable x. Then your loop changed that variable to 10.
I hope, I explained to you what happened. Please be understanding for me, I'm new here.
In JavaScript (EMCA-Script < 6) you can only create scopes with functions. Any other language construct won't create scope:
for(var i = 0; i < 10; i++) {}
// Logs 10 because "i" in the for loop doesn't create
// a block scope so "i" is available after the whole loop
console.log(i);
Since you've already declared an x before your for loop, and the whole loop uses x from 0 to 10, because for block won't create a scope, it's absolutely right that you get 10.
Scopes with functions:
function doStuff() {
// Inner scope
var a = 10;
}
// Outer scope
var a = 20;
x is 20 at start and then you change its value in a for cycle. The cycle changes its value to 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. At the end you have 10 as value, so the result you experienced is in fact the expected result.

Passing arguments to javascript function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript closure inside loops - simple practical example
javascript variable scope/closure in loop after timeout
Can you please explain step by step why the results are different?
Snippet A (alerts 10)
for(var i=0; i<10; i++) if(i==3) setTimeout(function() {alert(i);}, 100);
Snippet B (alerts 3)
for(var i=0; i<10; i++) if(i==3) setTimeout((function(p) {
return function() {alert(p);}
} )(i), 100);
A variable's scope is either the global scope (window in a browser) or a function.
In the first case i is defined in the scope containing the for loop. This is why it still changes until the end of the loop before the callback given to setTimeout is executed.
In the second case, the intermediate function contains and keeps another variable, p. Note that this would have worked without the test, as this would have been a different closure for each setTimeout.

Categories