Shaoz
Shaoz

Reputation: 10653

difference between using arr[i] and arr.length in the for loop definition in 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

Upvotes: 6

Views: 5873

Answers (5)

Pantelis
Pantelis

Reputation: 6136

Let's ask jsperf.com for this.

Upvotes: 2

Qtax
Qtax

Reputation: 33908

The for loop iterates as long as the condition part of it is true. First time the condition is false the loop stops.

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

i < arr.length checks that i is less than the size of the array, which is what you should do.

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359786

Using arr[i] as the continue condition checks the truthiness of the element at that position in the array. This is a cute trick, but won't work if you want to iterate over arrays containing falsy values, like

[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.

Upvotes: 1

Sascha Galley
Sascha Galley

Reputation: 16091

i < arr.length

this statement checks in every loop if i is smaller then the length of arr

arr[i]

here, every loop cycle checks if arr at position i is truthy.

Upvotes: 2

Amadan
Amadan

Reputation: 198324

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.

Upvotes: 12

Related Questions