Difference between using arr [i] and arr.length in the definition of the for loop in javascript

I came across something that I had never seen before, and I like it. check the examples below:

var arr = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept']; for(var i = 0; arr[i]; i++){ console.log( arr[i] ); } 

instead:

 for(var i = 0; i < arr.length; i++){ console.log( arr[i] ); } 

But both of them achieve the same result, which displays a list of arrays.

My question is, what is the difference (or similarity) between using "arr [i]" and "arr.length" in a declaration for a loop ?

Many thanks

+6
source share
5 answers
 var arr = ['un', 'deux', 'trois', null, 'cinq', 'six', 'sept']; 

What about?

 delete arr[2]; 

What about?

The difference occurs as soon as you have false values โ€‹โ€‹in the array or key breaks (for example, created using the delete operator). The length loop will give a false value and continue, the other will stop.

+11
source
 i < arr.length 

this operator checks in each cycle if i less than the length arr

 arr[i] 

here, each cycle of the cycle checks if arr at position i true.

+2
source
+2
source

Using arr[i] , because the continuation condition checks the likelihood of the element at this position in the array. This is a nice trick, but will not work if you want to iterate over arrays containing falsity values, e.g.

 [1, 4, 6, 0, 3, 9] // or [true, 'seven', false, -1, {foo: 'bar'}] 

Using i < arr.length checks that the current index is less than the total length of the array.

+1
source

The for loop iterates as long as the condition condition is met. The first time the condition is false, the cycle stops.

arr[i] true if the value is not one of the following: false, 0, empty string, null, undefined, NaN

i < arr.length checks that i less than the size of the array, what you need to do.

+1
source

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


All Articles