Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I've been programming in JavaScript for a long time, and "closure in a loop" is a very broad topic. I assume you are talking about the practice of using <code>(function(param) { return function(){ ... }; })(param);</code> inside of a for loop in order to preserve the "current value" of the loop when that inner function later executes...</p> <h2>The code:</h2> <pre><code>for(var i=0; i&lt;4; i++) { setTimeout( // argument #1 to setTimeout is a function. // this "outer function" is immediately executed, with `i` as its parameter (function(x) { // the "outer function" returns an "inner function" which now has x=i at the // time the "outer function" was called return function() { console.log("i=="+i+", x=="+x); }; })(i) // execute the "closure" immediately, x=i, returns a "callback" function // finishing up arguments to setTimeout , i*100); } </code></pre> <h2>Output:</h2> <pre><code>i==4, x==0 i==4, x==1 i==4, x==2 i==4, x==3 </code></pre> <p>As you can see by the output, all of the inner callback functions all point to the same <code>i</code>, however, since each had its own 'closure', the value of <code>x</code> is actually stored as whatever <code>i</code> was at the time of the outer function's execution. </p> <p>Commonly when you see this pattern, you would use the same variable name as the parameter and the argument to the outer function: <code>(function(i){ })(i)</code> for instance. Any code inside that function (even if executed later, like a callback function) is going to refer to <code>i</code> at the time you called the "outer function".</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload