which for loop has better performance in javascript? I can't find out which loop is better performance than another, if you know help me.

I try about loops in js and performance in this site
and this is code snippet, you can run and check.


const array1 = [];

for (let i = 0; i &lt;= 50000; i++) {
  array1.push(i);
}


//for...
var forT0 = performance.now()

for (let element = 0; element &lt; array1.length; element++) {
  console.log(element);
}

var forT1 = performance.now()
console.log("Call to doSomething took " + (forT1 - forT0) + " milliseconds.")



//for...in
var forInT0 = performance.now()

for (const element in array1) {
  console.log(element);
}

var forInT1 = performance.now()
console.log("Call to doSomething took " + (forInT1 - forInT0) + " milliseconds.")



//for...of
var forOfT0 = performance.now()

for (const element of array1) {
  console.log(element);
}


var forOfT1 = performance.now()
console.log("Call to doSomething took " + (forOfT1 - forOfT0) + " milliseconds.")


//forEach
var forEachT0 = performance.now()

array1.forEach(element =&gt; console.log(element));


var forEachT1 = performance.now()
console.log("Call to doSomething took " + (forEachT1 - forEachT0) + " milliseconds.")
Not sure if this is a right fit for this site, as this is clearly not 'real' code, but let me give you an answer anyway.

First, in your test code, the "for" case is clearly set up incorrectly. It should look more like this:

for (let i = 0; i &lt; array1.length; i++) {
  console.log(array1[i]);
}


Second, I don't think you are asking the right question. This is clearly a case of premature optimisation. There will be differences obviously, but in real life situations the difference will probably be marginal. It is much wiser to optimise for readability and developer comfort when writing code. Use the loop that makes most sense for you in your current situation. If you run into performance issues you can start looking at optimising then, but not before.

There are too many variables to draw conclusions from your test case. The size of the array you loop over for instance. On large arrays for will be probably be fastest (probably even a bit slower than a while loop). On small arrays a forEach is possibly faster, unless you do complex operations inside the loop. And all that is dependant on the javascript engine implementation and the hardware it runs on.

So as I said, don't worry about this stuff before you run into performance issues. And when you do, test your performance with real code and real data, not oversimplified testcode.