Passing arguments to javascript function [duplicate] - javascript

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.

Related

Understanding JavaScript scopes [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 5 years ago.
I'm trying to understand how scopes work in JS. Can you tell me if I correct with understanding of this chunk of code:
for(var i = 0; i<5; i++){
setTimeout(function timeoutHandler() {
var i = i;
console.log(i); //undefined
})
}
console.log prints undefined 5 times. So as I understand, when timeoutHandler is executed, it has its own local scope with own i variable. So is that correct that during timeoutHandler execution, the interpreter asks for i variable, finds it declared in local scope and uses this declared variable for assignment? This explains why it is undefined, but I'm not sure I'm fully correct.
Thanks
UPD
I don't need this code to work properly, I just want to understand why it behaves like that in this case
Trying to make sense of it by this example:
for(var i = 0; i<5; i++){
//create a self executing function
(function(iValue){
//in this scope iValue has the i from the loop
setTimeout(function() {
console.log(iValue); //will print the correct i
})
})(i); //pass i in it's current context to the function
}
Or easier with ES6:
Use let instead of var.
Since let is scoped within the block (each run of the loop is it's own block) it will not get another value inside the setTimeout.
for(let i = 0; i<5; i++){
setTimeout(function() {
console.log(i); //will print the correct i
})
}

its not printing 0,1,2,3,4,5...10 its printing 10 ten times [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 5 years ago.
I am new to js
I thought below code will output 0,1,2,3,4,5,6,7,8,9 with a gap of 10 ms.
but it's not printing like that it's printing 10 ten times.
is it due to set a timeout or something else?
can you guys tell me why it's happening...it will help me so much with understanding js
for( var i=0; i< 10; i++) {
setTimeout(function(){
console.log(i);
}, 10);
}
It's because of closure, you should do something like that
for( var i=0; i< 10; i++) {
(function(j){
setTimeout(function(){ console.log(j); }, 10);
}(i));
}
This is basic javascript closure, you can read more here How do JavaScript closures work?
The problem is that the for loop finishes first, so at the end, i will equal 10. After that, the setTimeout functions will get called and when they check the value of i, they'll find it equal to the last value from the for loop which 10.
What I did is called an IIFE (Immediately Invoked Function Expression) which creates a new variable for the scope of the setTimeout function, so when the timeout comes, it finds its own variable that hasn't changed.

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.

Why do functions defined in a loop all return the same value? [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 7 years ago.
I'm confused by the following JavaScript code. I wrote a loop and defined a function inside the loop, but when I call a function defined in the loop, I only get 10 rather than the index.
Obviously, in the following code I abstracted out stuff that isn't relevant:
objectArray = [];
for (i = 0; i< 10; i++){
objectArray[i] = {};
}
for (i = 0; i< 10; i++){
objectArray[i].get_number = function(){
return i;
}
}
console.log(objectArray[5].get_number()); // returns 10 rather than 5
I always get 10 rather than i as expected.
It's because of JavaScript closure. The method objectArray[i].get_number has direct access to i (not a copy of i). The value of i lives on in memory because each method objectArray[i].get_number still has access to it. There's only one i, and when the loop iterates it, it increases by one. When a method objectArray[i].get_number accesses it, the loop has already run to completion, so it accesses the final value of i.

Immediately Invoked Function Expression use case:inadvertent sharing via closures [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
var result=[];
for(var i=0;i<5;i++){
result.push(function () {return i});
}
console.log(result[1]()); //5 not 1
I think the result should be [0,1,2,3,4] and I don't understand why the value should be 5. How does it work? I am completely confused.
Because JavaScript does not have block scope, it has function scope. There is only one i variable, and it exists for the whole function. It is changed from 0, to 1, and so on, up to 5. All of the closures reference this same variable.
You can fix it by passing the value in to an immediately-invoked function that returns another function:
result.push((function (i) { return function() { return i; } }(i));
In this case you pass the value of i in to the outer function, which returns another function that returns the argument to this inner function, effectively capturing the value of the outer i at that particular moment.

Categories