Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how this for loop determines when to break the loop

I have encountered a different type of for loop which i don't see or use commonly.I tried to figure it out but get even more confused in the process.It doesn't have its third argument or even a check method to break the loop.Here it iterates over an array and prints its value.Actually it encounters 'undefined' value for a certain index but i am not telling it to break when it will encounter undefined.please help me to break the puzzle here...

(function () {
    var a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    for (var i = 0, value; value = a[i++];) {
        document.write(value + '</br>');
    }
})();
like image 663
AL-zami Avatar asked Feb 02 '26 04:02

AL-zami


1 Answers

In javascript, when you access array elements beyond the length of the array, you don't get a range check error, the returned value is undefined which corresponds to false when treated as boolean - thus the loop termination when the end of the array is reached.

If any of the array elements is undefined or any other value that becomes false as boolean, the loop will terminate on that element.

The assignment operator in javascript returns a value of the left side, so expression value = a[i++] is used to return the value of a[i] and increment i - in that order. If this value converts to false as boolean, the loop is terminated.

like image 169
Igor Avatar answered Feb 04 '26 18:02

Igor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!