Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 819
Shaoz Avatar asked Jun 14 '11 14:06

Shaoz


1 Answers

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.

like image 97
Amadan Avatar answered Nov 14 '22 22:11

Amadan