manhoty
manhoty

Reputation: 59

Is It ok to pass iterable[i] instead of iterable.length in loops

Should there be any concern of using

for(let i = 0; iterable[i];i++)

instead of

for(let i = 0; i < iterable.length; i++)

Upvotes: 0

Views: 35

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36564

Its not safe to write iterable[i] instead of i < iterable.length because the first method will check if iterable[i] is truthy or falsy and in javascript there are 6 falsy values. null, undefined, 0, '', NaN, false.

Consider you have array of numbers or strings and you use iterable[i] as loop condition. Then the loop will exit at empty string or 0. Also this way will cause serious issues while iterating over array of booleans.

But if you are looping over array of objects or array of another arrays then most probably it will not cause any problem but I will prefer to you use i < iterable.length.

Upvotes: 1

Related Questions