Javascript construct

I sometimes see constructs like this:

for (j = 1, len = arguments.length; j < len; j++) {

and the len variable is not anywhere else in the code. What would be a good reason to favor the above over this?:

for (j = 1; j < arguments.length; j++) {

Example taken from Leaflet (https://unpkg.com/leaflet@1.9.3/dist/leaflet-src.js).

The main reason to use the first construct over the second one is for performance reasons. When you access the arguments.length property inside the for loop, it needs to be re-evaluated on each iteration of the loop. This can lead to slightly slower performance, especially if the loop is being executed many times.

In the first construct, the value of arguments.length is evaluated once at the start of the loop, and then the variable len is used in the loop condition. This means that the loop condition is evaluating the value of a variable, which is generally faster than evaluating an expression.

Another benefit is that the first construct provides better readability of the code, at the cost of a tiny space complexity increase.

In general this is a micro-optimization, and the difference in performance is likely to be small in most cases. But in a high-performance or high-throughput context, this can make a significant difference over time.

It's important to note that the arguments object is not an array, it's similar but not exactly the same, and in many cases using arrays is more efficient and cleaner. The arguments object is mainly used for creating function that accept variable number of arguments, and using them with loops could lead to some issues, like not having the array methods available to you.

Understood. I already encountered an error when trying this, which to me seems like the most legible construct:

for (j in arguments) {

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.