I came across something I've never seen before and I like it. check examples below:
var arr = ['un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept'];
for(var i = 0; arr[i]; i++){
console.log( arr[i] );
}
instead of:
for(var i = 0; i < arr.length; i++){
console.log( arr[i] );
}
But they both achieve the same result, which is to output a list of array.
My question is, what's the difference (or similarity) between using 'arr[i]' and 'arr.length' in the for loop declaration?
Many thanks
var arr = ['un', 'deux', 'trois', null, 'cinq', 'six', 'sept'];
How about now?
delete arr[2];
How about now?
The difference shows up as soon as you have falsy values in the array, or discontinuities in keys (such as those created by using the delete
operator). The length
loop will yield the falsy value and continue, the other one will stop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With