0

I found this for loop in codepen . Why he used for loop like this ? 4 parameters ? His project is working . Please explain simple ,I am beginer . thank you

  timer = setInterval(function(){
    oCG.clearRect(0,0,1000,800);
    for(var i=0,l=aObj.length; i< l;i++){    <<<<======
      fnChange(aObj[i]);
      checkPeng(aObj,i);
    }
    
  },1000/60);
  • 3
    `,` isn't the same as `;` it still follows the general `for ([initialization]; [condition]; [final-expression]) statement` format of the for statement - just that there's two initialization statements, spearated by `,` – Bravo Aug 25 '21 at 04:10
  • how many do you need – Bravo Aug 25 '21 at 04:15
  • this is short cut for 2 for loops ? – student345 Aug 25 '21 at 04:19
  • 1
    In this particular case the reason is for performance. Detailed explanation here: http://simp.ly/p/mVLkH4 – Leftium Aug 25 '21 at 04:34
  • @Leftium why not just post that as an answer? that's a great explanation that shouldn't be buried in a comment link. -- **edit:** ah i see, because this question is closed. i'm voting to reopen. the linked duplicate does not include the context of using this as `for` loop initialization. – tdy Aug 26 '21 at 06:08
  • 1
    @tdy: Well, it started as an answer, but while I was writing the answer the question was closed as a duplicate. So I couldn't submit it. Vote to reopen this question! (And mark my original comment as helpful) – Leftium Aug 26 '21 at 06:14

2 Answers2

0

The fact is that he used a comma (,) in the first parameter (initialising variables) rather than a semicolon (;). This is used when declaring multiple variables at one time.

Matthias
  • 170
  • 15
0

i=0,l=aObj.length; is one part(initializing values for loop) where i and l values are fixed

i< l is the condition

i++ increment the value

therefore the ; is used for separating the parameters and , is used for adding in the same parameter

Ahmad
  • 816
  • 2
  • 9
  • 15