Skip to content
Advertisement

JavaScript – for Loop vs. Array shift

I have two functions, they do look alike but what I don’t really understand is when inside the for-loop, since the input is an array, why doesn’t the array need any index to call the first array?

I have an array of…

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; }
];

I’m trying to loop through the array with an input. The result of the first function will then be used as the next function’s input then the first array will be removed.

This is what I wrote…

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

The above does give me the answer but then I see that there’s another way of writing it which is

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

What I don’t understand is the part input = queue.shift()(input).

Doesn’t the queue need an index?

Advertisement

Answer

So you’re basically asking what shift does and here you go:
What you can do using for(var i=0;… you can do using shift() (quite similar but not!)

Using for loop (and index)

var array = [
  function(){return "a";},
  function(){return "b";}
];
  
for(var i=0; i<array.length; i++){
    console.log( array[i]() );  
    // "a"
    // "b"
}

console.log(array.length); //2       !!Still there!!!

Using shift() (and while for example)

var array = [
  function(){return "a";},
  function(){return "b";}
];
  
while(array.length){                // while array has length
    console.log( array.shift()() );  // execute and remove from array
    // "a"
    // "b"
}

console.log(array.length); //0   !!!Empty array due to shift()!!!

So basically it removes a key from your Array and returns it.
As long as that array has keys it will loop until it’s empty.

The difference between the two is drastic:
The for loop in example 1. will loop but not alter your original array.
Using shift() in example 2. you’re (using and) removing your Array keys one by one.

Read more about Array manipulation:

Array.prototype.shift 1 <-- [2,3,4]
Array.prototype.unshift 5 --> [5,2,3,4]
Array.prototype.push [5,2,3,4,6] <-- 6
Array.prototype.pop [5,2,3,4] --> 6

and other Methods

Advertisement