Difference between two iterations of an array

I'm just curious to know the difference between these iterations of the array, and why does the second seem to be very rarely used, is something wrong with it?

var items = [ /*...*/ ] for (var i = 0; i < items.length; i++) { var item = items[i]; // Do some stuff with the item } 

The second way:

 var items = [ /*...*/ ] for (var i, item; item = items[i]; i++) { // Do some stuff with the item } 
+4
source share
3 answers

The first is guaranteed to always go through each element.

The second will be stopped halfway if it encounters some false-like element, for example 0.

+9
source

In the second for loop, you need to initialize your i variable.

Consider:

 var items = ["string", false, null, 0, "", {}, []]; 

The first loop will go through the entire array. However, the second condition of the loop will evaluate the value assigned to the element. The boolean value of this part will be:

 !!(item = items[i]) 

valid values ​​such as null , 0 , false , "" (empty string) and undefined will evaluate to false and break. In the array above, you exit the for loop when the element is set to false

+1
source

In the second case, the termination condition is somewhat javascript-specific - the loop ends when the assignment is converted to boolean yields false , which also happens when an array element is read from its borders. This contradicts other popular languages ​​in which access to the array due to bouns causes some error and does not guarantee the correct condition for ending the loop for . When any programmer with a background in languages ​​other than javascript writes an iteration loop, he probably avoids patterns that he knows are incorrect or even dangerous in those languages.

That will be the main reason, I think. But, as mentioned above, the other thing is that this condition can be false even before the end of the iterated array is reached - for example, when the assigned element is false , 0 or any other value that is implicitly converted to false in javascript.

0
source

Source: https://habr.com/ru/post/1440620/


All Articles