Groovepig
Groovepig

Reputation: 69

Javascript while loop with function as conditional

My understanding is that the contents of a while loop executes while the condition is true. While working off of an example from an awesome O'Riely book, I've come across this implementation of the while loop...

window.onload = function(){

    var next, previous, rewind; //  globals

    (function(){
        //  Set private variables
        var index = -1;
        var data = ['eeny', 'meeny', 'miney', 'moe'];
        var count = data.length;

        next = function(){
            if (index < count) {
                index ++;
            };
            return data[index];
        };

        previous = function(){
            if (index <= count){
                index --;
            }
            return data[index];
        };

        rewind = function(){
            index = -1;
        };

    })();

    //  console.log results of while loop calling next()...
    var a;
    rewind();
    while(a = next()){
        //  do something here
        console.log(a);
    }


}

I guess I'm wondering why, in this code, the while loop is not resolving to true infinitely? The function, next() isn't returning false after var index stops incrementing (++), is it? Shouldn't the console just be outputting eeny, meeny, miney, moe, moe, moe, moe.....etc...

I know this has probably been asked in some form, but have done searching and can't find a question or answer that explains using while (a = function()) {// do something} and how this loop is stopping after one pass through the array.

Upvotes: 4

Views: 3697

Answers (3)

Qantas 94 Heavy
Qantas 94 Heavy

Reputation: 16020

About why while (a = next()) {/*do something*/} doesn't repeat infinitely, it's about being coerced to false that counts - arguments are converted to booleans before being tested by the while loop. Things that coerce to false include 0, -0, undefined, null, "", NaN, and of course false itself.

When you assign something, it returns the value of the assignment itself. For example, if you do something like this:

var a;
console.log(a = '1234567890abcdefghijklmnopqrstuvwxyz');

It will log 1234567890abcdefghijklmnopqrstuvwxyz.

When the next performs index++, this increments the counter for the element index in the data array. This means that it will look for the next element in the data array every time you run the next() function - if there are no more elements, it will return undefined and therefore end the loop.

For example, see this:

var index = 0;
data = ['a','b','c'];
data[index]; // 'a'
index++;
data[index]; // 'b'
index++;
data[index]; // 'c'
index++;
data[index]; // undefined - if passed this will coerce to false and end the loop
Boolean(data[index]); // false

Upvotes: 3

Hozikimaru
Hozikimaru

Reputation: 1156

No,

It is not going to be an infinite loop. The while loop is basically going through the array and outputting it and when it is at the end of the array it just returns false and quits the loop.

This is something like;

foreach(a as nextArray)
{
//output
}

Hope this helps.

Upvotes: 1

tckmn
tckmn

Reputation: 59273

if (index < count) {
    index ++;
};

When index is count - 1, this will still change index to count, right? And count is data.length. So, it then does this:

return data[index];

Which becomes

return data[data.length];

Since the length of an array is out of bounds of the array (they are zero-based), it will give undefined.

while(a = next()){

will become

while(a = undefined){

Since undefined is a falsy value, the loop will not be entered.

Upvotes: 1

Related Questions