Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript loop best practice

I'm doing a tutorial on JavaScript. The following is from a section on performance:

Each statement in a loop, including the for statement, is executed for each iteration of the loop. Statements or assignments that can be placed outside the loop will make the loop run faster.

This is given as an example of bad code:

var i;
for (i = 0; i < arr.length; i++) {

And this is given as an example of good code:

var i;
var l = arr.length;
for (i = 0; i < l; i++) {

This is not something I can remember seeing as a best practice in languages that are more focused on performance than JavaScript. In fact, the bad code example seems to be preferred.

Is this best practice something particular for JavaScript, or is is true for other languages?

like image 358
Q-bertsuit Avatar asked Jul 19 '26 11:07

Q-bertsuit


1 Answers

Bad Practice

for (i = 0; i < arr.length; i++) {

For every iteration in the loop, the condition is evaluated. If it is being arr.length then every time you are trying to access length property from arr. However, on the other hand, if you are storing it in a variable you are avoiding that operation.

like image 163
Nikhil Aggarwal Avatar answered Jul 21 '26 01:07

Nikhil Aggarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!