Skip to content

Instantly share code, notes, and snippets.

@nicolo-ribaudo
Last active June 4, 2023 20:49
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicolo-ribaudo/827cf93b96944fca10b4126d752ed5bb to your computer and use it in GitHub Desktop.
Save nicolo-ribaudo/827cf93b96944fca10b4126d752ed5bb to your computer and use it in GitHub Desktop.

This for loop:

for (let i = 0, getI = () => i; i < 3; i++)
  console.log(getI());

unrolls to:

let i_initial = 0, getI_initial = () => i_initial;
{
  let i_iteration0 = i_initial;
 
  // TEST: i_iteration0 < 3 --> TRUE

  let getI_iteration0 = getI_initial;
  console.log(getI_iteration0());

  {
    let i_iteration1 = i_iteration0;
    let getI_iteration1 = getI_iteration0;
    
    i_iteration1++;
    
    // TEST: i_iteration1 < 3 --> TRUE
  
    console.log(getI_iteration1());

    {
      let i_iteration2 = i_iteration1;
      let getI_iteration2 = getI_iteration1;
      
      i_iteration2++;
      
      // TEST: i_iteration2 < 3 --> TRUE
    
      console.log(getI_iteration2());
      
      {
        let i_iteration3 = i_iteration2;
        let getI_iteration3 = getI_iteration2;
      
        i_iteration3+;

        // TEST: i_iteration3 < 3 --> FALSE
      }
    }
  }
}
@phsultan
Copy link

phsultan commented Nov 13, 2022

Doesn't it unroll to something like this instead?

let i_initial = 0, getI_initial = () => i_initial;
// TEST: i_initial < 3 --> TRUE
{
  let i_iteration0 = i_initial;
  let getI_iteration0 = getI_initial;
  console.log(getI_iteration0());
  i_iteration0++;
  
  // TEST: i_iteration0 < 3 --> TRUE
  {
    let i_iteration1 = i_iteration0;
    let getI_iteration1 = getI_iteration0;
    console.log(getI_iteration1());
    i_iteration1++;
    
    // TEST: i_iteration1 < 3 --> TRUE
    {
      let i_iteration2 = i_iteration1;
      let getI_iteration2 = getI_iteration1;
      console.log(getI_iteration2());
      i_iteration2++;      

      // TEST: i_iteration2 < 3 --> FALSE
    }
  }
}

@nicolo-ribaudo
Copy link
Author

@phsultan Neither my original version nor your are entirely correct! I updated the gist; it now runs the test before running the loop body (as you suggested); however the test should run with the new variables and not with the ones from the previous iteration.

@phsultan
Copy link

Ah I understand the initialisation is a bit subtle indeed. Thanks a lot for sharing this simple but tricky case Nicolò, much insightful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment