J.Iaconis J.Iaconis - 25 days ago 3
Javascript Question

Why is length defined as a variable instead of using queue.length in the for loop?

I am making my way through Code School's JavaScript Road Trip courses, and this lesson is the first one that is really giving me a hard time. This is the solution they provided for part 3 - level 1 - challenge 13.



var puzzlers = [
function(a) { return 8 * a - 10; },
function(a) { return (a - 3) * (a - 3) * (a - 3); },
function(a) { return a * a + 4; },
function(a) { return a % 5; }
];
var start = 2;

var applyAndEmpty = function(input, queue) {
var length = queue.length;
for (var i = 0; i < length; i++) {
input = queue.shift()(input);
}
return input;
};

alert(applyAndEmpty(start, puzzlers));





I don't understand why they create a variable called
length
. Initially, I would have thought to simply use
i < queue.length
in the
for
loop. So, why is it declared as a variable before the
for
loop?

Additionally, I am really confused by what is happening in the
for
loop.

For reference, this was my code before I got the answer from codeschool:



var puzzlers = [
function(a) { return 8 * a - 10; },
function(a) { return (a - 3) * (a - 3) * (a - 3); },
function(a) { return a * a + 4; },
function(a) { return a % 5; }
];
var start = 2;

var applyAndEmpty = function(input, queue){
for (var i=0; i<queue.length; i++){
queue.shift(input);
};
}

alert(applyAndEmpty(start, puzzlers));





First time posting, so please forgive me if I'm doing anything wrong.

Answer

So why is it declared as a variable before the for loop?

For not reading the length property in each iteration. It makes sense to cache the length property for huge arrays, but here it's somehow a premature-optimization. One can also cache the variable in the for loop:

for (var i = 0, length = queue.length; i < length; i++) {
   input = queue.shift()(input);
}

Well, the above paragraph is not correct in this case. Since the the for loop executes the second expression in each iteration, without caching the length property the loop doesn't work properly as the loop body modifies the length of the array by calling the shift method.

The code simply passes the input to each function in the array sequentially. The returned value of each function is passed to the next function. It works like the Array.prototype.reduce function. Knowing how the Array.prototype.shift function and the invocation operator (()) works will help you to better understand the code.

// remove the first element from the array and return it
let functionReference = queue.shift();
// call the function by using `()` operator and update the input
input = functionReference(input);