JavaScript - Optimize Loops

Impact area

Performance

Severity

Warning

Affected element

All

Rule number

SN-0104

Impact

Evaluating the length of an array each time it is iterated through is inefficient.

Remediation

Store the length of the array in a variable and use the variable in the evaluation statement.

Time to fix

10 min

Code examples

Noncompliant code

var names = ['George', 'Ringo', 'Paul', 'John']; for(var i=0;i<names.length;i++){ doSomethingWith(names[i]); }

Compliant code

var names = ['George', 'Ringo', 'Paul', 'John']; for(var i=0,j=names.length;i<j;i++){ doSomethingWith(names[i]); }




Last modified on Nov 28, 2022